前一篇文章介绍直接调用ui文件,本文介绍将ui文件转成py文件生成窗口的编程方式。要将MyForm.ui生成ui_MyForm.py文件,需执行下列命令:
pyuic5.bat MyForm.ui -о ui_MyForm.py
生成.py文件后,就可用import导入到程序中:
from PyQt5 import QtWidgets
import sys, ui_MyForm
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
ui = ui_MyForm.Ui_MyForm()
ui.setupUi(window)
ui.btnQuit.clicked.connect(QtWidgets.qApp.quit)
window.show()
sys.exit(app.exec_())
以上是使用函数编程方式的代码。
ui = ui_MyForm.Ui_MyForm()
创建窗口对象,然后调用setupUi 函数,参数为窗口实例:
ui.setupUi(window)
也可采用面向对象的编程方式:
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
import ui_MyForm
class MyWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = ui_MyForm.Ui_MyForm()
self.ui.setupUi(self)
self.ui.btnQuit.clicked.connect(QtWidgets.qApp.quit)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
还可将该窗口作为父类,创建新窗口:
from PyQt5 import QtWidgets
import ui_MyForm
class MyWindow(QtWidgets.QWidget, ui_MyForm.Ui_MyForm):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setupUi(self)
self.btnQuit.clicked.connect(QtWidgets.qApp.quit)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())