本教程展示了如何使用一些基本的小部件构建一个简单的对话框。这个想法是让用户在QLineEdit中提供他们的名字,然后点击QPushButton,对话框就会向他们打招呼。
让我们从创建并显示对话框的简单存根开始。此存根将在本教程的过程中更新,但如果需要,可以按原样使用此存根:
import sys
from PySide6.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())
导入对您来说并不新鲜,创建QApplication和执行Qt主循环也是如此。这里唯一的新奇之处是类定义。
您可以创建任何将PySide6小部件子类化的类。在本例中,我们将QDialog子类化以定义一个自定义对话框,我们将其命名为Form。我们还实现了init()方法,该方法使用父控件调用QDialog的init方法(如果有的话)。另外,新的setWindowTitle()方法只设置对话框窗口的标题。在main()中,您可以看到我们正在创建一个表单对象并向世界展示它。
创建小部件
我们将创建两个小部件:一个QLineEdit,用户可以在其中输入他们的名称;一个QPushButton,打印QLineEdit的内容。因此,让我们将以下代码添加到表单的init()方法中:
# Create widgets
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")
从代码中可以明显看出,两个小部件都将显示相应的文本。
创建一个布局来组织小部件
Qt附带了布局支持,可以帮助您组织应用程序中的小部件。在本例中,让我们使用QVBoxLayout来垂直布局小部件。创建小部件后,将以下代码添加到init()方法:
# Create layout and add widgets
layout = QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
因此,我们创建布局,使用addWidget()添加小部件。
创建greet函数连接到按钮
最后,我们只需要在自定义表单中添加一个函数,并将按钮连接到它。我们的函数将是表单的一部分,因此您必须将其添加到init()函数之后:
# Greets the user
def greetings(self):
print(f"Hello {self.edit.text()}")
我们的函数只是将QLineEdit的内容打印到python控制台。我们可以通过QLineEdit.text()访问文本。
现在我们已经拥有了一切,只需要将QPushButton连接到Form.greetings()方法。为此,在init()方法中添加以下行:
# Add button signal to greetings slot
self.button.clicked.connect(self.greetings)
执行后,您可以在QLineEdit中输入您的姓名,并查看控制台中的问候语。
完整代码
以下是本教程的完整代码:
import sys
from PySide6.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(f"Hello {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())
当您执行代码并写下您的姓名时,该按钮将在终端上显示消息: