本教程展示了如何构建一个简单的对话框与一些基本的小部件。
这个想法是为了让用户提供他们的名字在QLineEdit和问候他们的对话框单击QPushButton。
让我们开始用一个简单的存根,创建并显示一个对话框。更新该存根在本教程中,但您可以使用此存根是如果你需要:
import sysfrom PySide6.QtWidgets import QApplication, QDialog, QLineEdit, QPushButtonclass Form(QDialog):def __init__(self, parent=None):super(Form, self).__init__(parent)self.setWindowTitle("My Form")if __name__ == '__main__':# Create the Qt Applicationapp = QApplication(sys.argv)# Create and show the formform = Form()form.show()# Run the main Qt loopsys.exit(app.exec())
这个对于你来说不新鲜了,QApplication的创建和Qt的执行主循环。这里唯一的新奇是init 类的定义方式 包含了继承
通过继承pyside6的子类部件创建。现在我们把QDialog 继承子类,并且定义成Form 类。我们实例化init()方法,init 会先初始化 父类中的init。此外setWindowTitle()方法 可以设置对话框窗口的标题。在main()中,您可以看到,我们正在创建一个表单对象
创建一个Widgets
# Create widgetsself.edit = QLineEdit("Write my name here..")self.button = QPushButton("Show Greetings")
创建 layout 并布局 widgets
# Create layout and add widgetslayout = QVBoxLayout(self)layout.addWidget(self.edit)layout.addWidget(self.button)
所以,我们使用QVBoxLayout创建布局,通过addWidget() 添加小部件
创建一个函数来迎接并连接按钮
最后,我们只需要添加一个函数去定制化一下Form类 ,并将它和按钮绑定。
我们的函数是Form类的一部分,所以你必须将它添加在init()函数后面
# Greets the userdef greetings(self):print(f"Hello {self.edit.text()}")
greetings函数只是通过QLineEdit.text()方法打印的内容到python控制台
现在我们只需要连接的QPushButton和Form.greetings()方法。在Form 的 init()方法中添加以下行:
# Add button signal to greetings slotself.button.clicked.connect(self.greetings)
完整的代码:
import sysfrom PySide6.QtWidgets import (QLineEdit, QPushButton, QApplication,QVBoxLayout, QDialog)class Form(QDialog):def __init__(self, parent=None):super(Form, self).__init__(parent)# Create widgetsself.edit = QLineEdit("Write my name here")self.button = QPushButton("Show Greetings")# Create layout and add widgetslayout = QVBoxLayout()layout.addWidget(self.edit)layout.addWidget(self.button)# Set dialog layoutself.setLayout(layout)# Add button signal to greetings slotself.button.clicked.connect(self.greetings)# Greets the userdef greetings(self):print(f"Hello {self.edit.text()}")if __name__ == '__main__':# Create the Qt Applicationapp = QApplication(sys.argv)# Create and show the formform = Form()form.show()# Run the main Qt loopsys.exit(app.exec())
