创建一个对话框应用程序

本教程展示了如何使用一些基本小部件构建一个简单的对话框。目的是让用户在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()中,你可以看到 我们正在创建一个Form对象并将其显示出来。

创建小部件

我们将创建两个小部件:一个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()添加小部件。

创建用于问候并连接按钮的函数

最后,我们只需要在我们的自定义表单中添加一个函数,并将我们的按钮连接到它。我们的函数将是表单的一部分,因此你必须在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())

当你执行代码并写下你的名字时,按钮将在终端上显示消息:

Simple Dialog Example