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()函數(shù),用于在按鈕被點擊時調用。之后,初始化了一個QPushButton類,并通過類的QPushButton的方法將點擊時要執(zhí)行的動作函數(shù)與此綁定。
每點擊一次,在控制臺輸出一串字符,如下圖所示:

Snipaste_2018-11-02_14-36-59.png
如果希望點擊按鈕時退出程序,可以調用QApplication實例的exit函數(shù),即通過以下語句實現(xiàn):
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.創(chuàng)建圖形組件
self.edit = QLineEdit('Write my name here...')
self.button = QPushButton("Show Greetings")
以上創(chuàng)建了兩個圖形組件
2.創(chuàng)建布局管理器,用于對組件進行添加和布局管理
layout = QVBoxLayout()
3.將組件加入布局管理器
layout.addWidget(self.edit)
layout.addWidget(self.button)
4.將布局管理添加到父級組件上
self.setLayout(layout)
以上步驟都需要在類的初始化時完成,所以應將以上代碼全部放入Form類的init()方法的最后。
定義按鈕的動作函數(shù)并綁定至按鈕
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