本教程展示了如何构建一个简单的对话框与一些基本的小部件。
这个想法是为了让用户提供他们的名字在QLineEdit和问候他们的对话框单击QPushButton。
让我们开始用一个简单的存根,创建并显示一个对话框。更新该存根在本教程中,但您可以使用此存根是如果你需要:

  1. import sys
  2. from PySide6.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton
  3. class Form(QDialog):
  4. def __init__(self, parent=None):
  5. super(Form, self).__init__(parent)
  6. self.setWindowTitle("My Form")
  7. if __name__ == '__main__':
  8. # Create the Qt Application
  9. app = QApplication(sys.argv)
  10. # Create and show the form
  11. form = Form()
  12. form.show()
  13. # Run the main Qt loop
  14. sys.exit(app.exec())

这个对于你来说不新鲜了,QApplication的创建和Qt的执行主循环。这里唯一的新奇是init 类的定义方式 包含了继承

通过继承pyside6的子类部件创建。现在我们把QDialog 继承子类,并且定义成Form 类。我们实例化init()方法,init 会先初始化 父类中的init。此外setWindowTitle()方法 可以设置对话框窗口的标题。在main()中,您可以看到,我们正在创建一个表单对象

创建一个Widgets

  1. # Create widgets
  2. self.edit = QLineEdit("Write my name here..")
  3. self.button = QPushButton("Show Greetings")

很明显从代码这两个小部件将显示相应的文本。

创建 layout 并布局 widgets

  1. # Create layout and add widgets
  2. layout = QVBoxLayout(self)
  3. layout.addWidget(self.edit)
  4. layout.addWidget(self.button)

所以,我们使用QVBoxLayout创建布局,通过addWidget() 添加小部件

创建一个函数来迎接并连接按钮

最后,我们只需要添加一个函数去定制化一下Form类 ,并将它和按钮绑定。
我们的函数是Form类的一部分,所以你必须将它添加在init()函数后面

  1. # Greets the user
  2. def greetings(self):
  3. print(f"Hello {self.edit.text()}")

greetings函数只是通过QLineEdit.text()方法打印的内容到python控制台
现在我们只需要连接的QPushButton和Form.greetings()方法。在Form 的 init()方法中添加以下行:

  1. # Add button signal to greetings slot
  2. self.button.clicked.connect(self.greetings)

完整的代码:

  1. import sys
  2. from PySide6.QtWidgets import (QLineEdit, QPushButton, QApplication,
  3. QVBoxLayout, QDialog)
  4. class Form(QDialog):
  5. def __init__(self, parent=None):
  6. super(Form, self).__init__(parent)
  7. # Create widgets
  8. self.edit = QLineEdit("Write my name here")
  9. self.button = QPushButton("Show Greetings")
  10. # Create layout and add widgets
  11. layout = QVBoxLayout()
  12. layout.addWidget(self.edit)
  13. layout.addWidget(self.button)
  14. # Set dialog layout
  15. self.setLayout(layout)
  16. # Add button signal to greetings slot
  17. self.button.clicked.connect(self.greetings)
  18. # Greets the user
  19. def greetings(self):
  20. print(f"Hello {self.edit.text()}")
  21. if __name__ == '__main__':
  22. # Create the Qt Application
  23. app = QApplication(sys.argv)
  24. # Create and show the form
  25. form = Form()
  26. form.show()
  27. # Run the main Qt loop
  28. sys.exit(app.exec())