Pyqt5:builtins.AttributeError:' QDialog'对象没有属性' setCentralWidget'

时间:2016-08-24 21:50:16

标签: python-3.x user-interface pyqt5

我从Pyqt5设计师转换了ui文件:

Testing1.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(380, 180, 112, 34))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Test1.py <是为了添加方法等等。

import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from testing1 import Ui_MainWindow

class myprog(Ui_MainWindow):
    def __init__ (self, dialog):
        Ui_MainWindow.__init__(self)
        self.setupUi(dialog)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    dialog = QtWidgets.QDialog()

    test1 = myprog(dialog)
    dialog.show()
    sys.exit(app.exec_())

如果我运行Testin1.py它一切正常,但如果运行第二个脚本test1.py,我收到以下消息:

> builtins.AttributeError: 'QDialog' object has no attribute
> 'setCentralWidget'

我真的很困惑该怎么做,我真的很感激,如果你能帮我解决这个问题。任何帮助都非常受欢迎。

1 个答案:

答案 0 :(得分:2)

Testing1.py 文件中,您可以创建一个MainWindow。 因此,在 Test1.py 文件中,您应该更改代码

dialog = QtWidgets.QDialog()

dialog = QtWidgets.QMainWindow()