用QtDesigner设计了一个UI界面,保存在文件Ui_wintest.ui中,界面中使用了MainWindow窗口,窗口名字也叫MainWindow,用PyUIC将其转换成了
Ui_wintest.py文件,在其中UI界面类为Ui_MainWindow。
然后编辑了一个主应用代码文件:
from PyQt5.QtWidgets import QMessageBox,QApplication
from PyQt5 import QtWidgets
import sys
import Ui_wintest
showMessage = QMessageBox.question
class winTest(QtWidgets.QWidget,Ui_wintest.Ui_MainWindow ):
def __init__(self):
super(winTest, self).__init__()
self.setupUi(self)
def closeEvent(self,event):
reply = showMessage(self, '警告',"系统将退出,是否确认?", QMessageBox.Yes |QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = winTest()
w.show()
sys.exit(app.exec_())
使用Pycharm进行代码检测没有错误,但执行时报错:
AttributeError: ‘winTest’ object has no attribute ‘setCentralWidget’
经确认是因为主程序的类派生的基类使用错了导致,由于UI界面设计使用了MainWindow,因此在主程序派生的子类必须继承MainWindow,将类定义的语句改成为:
class winTest(QtWidgets.QMainWindow,Ui_wintest.Ui_MainWindow ):
就可以了,同样的,如果UI设计使用的窗口类型是其他类型,最好在主程序派生类的定义时基类就要使用对应类型。

博客地址:https://blog.****.net/LaoYuanPython
老猿Python博客文章目录:https://blog.****.net/LaoYuanPython/article/details/98245036