Pyqt 简明教程

PyQt - Using Qt Designer

PyQt 安装程序附带了一个名为 Qt Designer 的 GUI 构建工具。利用其简单的拖放界面,可以快速构建 GUI 界面而无需编写代码。然而,它不是像 Visual Studio 这样的 IDE。因此,Qt Designer 没有调试和构建应用程序的功能。

The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application.

使用 Qt Designer 创建 GUI 界面始于为应用程序选择一个顶级窗口。

Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application.

qt designer1

然后,您可以从左侧窗格中的小部件框中拖放所需の小部件。您还可以将值分配给布置在窗体上的小部件的属性。

You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form.

qt designer2

设计好的窗体将另存为 demo.ui。此 ui 文件包含设计中对应小部件及其属性的 XML 表示。使用 pyuic4 命令行实用程序将此设计转换为 Python 等效项。此实用程序是 uic 模块的包装器。pyuic4 的用法如下 −

The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic4 command line utility. This utility is a wrapper for uic module. The usage of pyuic4 is as follows −

pyuic4 –x demo.ui –o demo.py

在上文中,-x 开关向生成的 XML 中添加少量附加代码,以便使其成为一个可独立自执行的应用程序。

In the above command, -x switch adds a small amount of additional code to the generated XML so that it becomes a self-executable standalone application.

if __name__ == "__main__":
   import sys
   app = QtGui.QApplication(sys.argv)
   Dialog = QtGui.QDialog()
   ui = Ui_Dialog()
   ui.setupUi(Dialog)
   Dialog.show()
   sys.exit(app.exec_())

执行结果 Python 脚本以显示以下对话框 −

The resultant python script is executed to show the following dialog box −

dialog box

用户可以在输入字段中输入数据,但单击“添加”按钮不会生成任何操作,因为它不与任何函数关联。对用户生成的响应作出反应被称为 event handling

The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling.