1. 设计UI界面
Qt Designer的保存路径在
C:\Users\u0013662\AppData\Local\Programs\Python\Python36\Lib\site-packages\pyqt5-tools
打开QtDesigner,新建一个“Dialog Without Buttons”
从左侧的WidgetBox拖入一个Label,一个Text和一个Button
文件保存为test.ui
2. 使用pyuic5将.ui文件转换为.py文件。
在CMD窗口下执行命令:pyuic5 test.ui –o test.py
如果执行成功,在同目录下生成test.py文件
内容如下:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(130,70, 81, 18))
self.label.setObjectName("label")
self.pushButton =QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(140, 210, 112, 34))
self.pushButton.setObjectName("pushButton")
self.lineEdit =QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(100, 130, 171, 41))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate =QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog","Dialog"))
self.label.setText(_translate("Dialog","TextLabel"))
self.pushButton.setText(_translate("Dialog","PushButton"))
这个程序定义的是各个界面元素和它们的位置、名称、标签等信息,当然,Qt Designer也可以通过信号和槽的机制为控件添加响应事件,在此文暂不介绍。
3. 编写执行程序load.py
import sys
from test import *
fromPyQt5.QtWidgets import *
classMyWidgets(Ui_Dialog):
def setupUi(self,Dialog):
super().setupUi(Dialog)
self.pushButton.clicked.connect(self.A)
def A(self,Dialog):
try:
EditText=self.lineEdit.text()
_translate =QtCore.QCoreApplication.translate
self.label.setText(_translate("Dialog", EditText))
except:
print(sys.exc_info())
if__name__ == '__main__':
app=QtWidgets.QApplication(sys.argv)
Form=QtWidgets.QWidget()
ui=MyWidgets()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
这个程序新定义了一个类MyWidgets,MyWidgets继承自test.py中的类Ui_Dialog,首先它重写了setupUi方法,重写这个方法是为了为Button绑定触发事件,当然,它要先执行super().setupUi(Dialog)把父类的整个方法继承过来,再加入self.pushButton.clicked.connect(self.A)用于绑定事件。A方法是MyWidgets的成员函数,具体实现按钮动作。
if__name__ == '__main__':
app=QtWidgets.QApplication(sys.argv)
Form=QtWidgets.QWidget()
ui=MyWidgets()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
这段是程序执行的入口,由于MyWidgets的setupUi方法要求一个Dialog参数,因此Form=QtWidgets.QWidget()声明一个Form, 再生成一个MyWidgets实例,执行SetupUi构造整个页面,执行Form.show()显示界面。
有一个问题,整个程序操作的是Object的子类Ui_Dialog,可为什么调用Form,show()来显示界面呢?注意类似self.pushButton= QtWidgets.QPushButton(Dialog)声明控件时总有一个参数Dialog,可以这样理解,pushButton是UI_Dialog的属性,它指的是Dialog上的一个界面元素。这本身就是一个显示和操作分离的逻辑。
4. 这可以作为一个程序开发框架。
(1) 用QT Desinger设计界面生成ui
(2) 用pyuic5把ui转成界面py
(3) 编写界面py的子类,在子类里定义并绑定控件的动作
(4) 编写程序执行入口,执行程序。