官方提供的基礎指南二
4.按鈕使用
import sys from PySide2.QtWidgets import QApplication, QPushButton def say_hello(): print("Button clicked, Hello!") # Create the Qt Application app = QApplication(sys.argv) # Create a button, connect it and show it button = QPushButton("Click me") button.clicked.connect(say_hello) button.show() # Run the main Qt loop app.exec_()
程式中先定義了say_hello()函式,用於在按鈕被點選時呼叫。之後,初始化了一個QPushButton類,並通過類的QPushButton的方法將點選時要執行的動作函式與此繫結。
每點選一次,在控制檯輸出一串字元,如下圖所示:

Snipaste_2018-11-02_14-36-59.png
如果希望點選按鈕時退出程式,可以呼叫QApplication例項的exit函式,即通過以下語句實現:
button.clicked.connect(app.exit)
5.對話方塊使用
程式的基本框架
程式碼如下:
import sys from PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.setWindowTitle("My Form") if __name__ == '__main__': # Create the Qt Application app = QApplication(sys.argv) # Create and show the form form = Form() form.show() # Run the main Qt loop sys.exit(app.exec_())
與之前的程式有所不同:程式中自定義了一個Form類,繼承了QDialog類。並在類中呼叫了父類的初始化方法和從父類繼承而來的setWindowTitle()方法,設定了視窗的標題。
其餘部分與之前例項結構相同。
新增其他圖形元件
新增圖形元件有四個基本步驟:
1.建立圖形元件
self.edit = QLineEdit('Write my name here...') self.button = QPushButton("Show Greetings")
以上建立了兩個圖形元件
2.建立佈局管理器,用於對元件進行新增和佈局管理
layout = QVBoxLayout()
3.將元件加入佈局管理器
layout.addWidget(self.edit) layout.addWidget(self.button)
4.將佈局管理新增到父級元件上
self.setLayout(layout)
以上步驟都需要在類的初始化時完成,所以應將以上程式碼全部放入Form類的 init ()方法的最後。
定義按鈕的動作函式並繫結至按鈕
def greetings(self): print("Hello {}".format(self.edit.text()))
然後使用button的屬性繫結greeting方法:
self.button.clicked.connect(self.greetings)
完整的程式碼如下:
import sys from PySide2.QtWidgets import (QLineEdit, QPushButton, QApplication, QVBoxLayout, QDialog) class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) # Create widgets self.edit = QLineEdit("Write my name here") self.button = QPushButton("Show Greetings") # Create layout and add widgets layout = QVBoxLayout() layout.addWidget(self.edit) layout.addWidget(self.button) # Set dialog layout self.setLayout(layout) # Add button signal to greetings slot self.button.clicked.connect(self.greetings) # Greets the user def greetings(self): print ("Hello %s" % self.edit.text()) if __name__ == '__main__': # Create the Qt Application app = QApplication(sys.argv) # Create and show the form form = Form() form.show() # Run the main Qt loop sys.exit(app.exec_())
執行效果如下圖:

Snipaste_2018-11-02_15-13-15.png