Qt5: AttributeError: 'module' object has no attribute 'QApplication'

Qt5: AttributeError: 'module' object has no attribute 'QApplication'

系统:15.10(狡猾的狼人)x64

代码:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(120, 120, 85, 26))
        self.pushButton.setObjectName("pushButton")

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

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

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_Form()
    ex.show()
    sys.exit(app.exec_())

我收到以下错误:

    app = QtGui.QApplication(sys.argv)
AttributeError: 'module' object has no attribute 'QApplication'

基本上我是用Qt5设计的GUI然后用pyuic5。我已经安装了 PyQt5,不确定安装是否按预期进行。

UI设计:

非常感谢任何帮助。

我不确定您的主要功能是如何生成的。我试图用似乎是相同版本的 pyuic5 来复制它。我用命令行 pyuic5 -x untitled.ui 调用它(其中 ui 在你的例子中只包含一个小部件中的按钮)。 -x选项的作用是:'The generated Python code includes a small amount of additional code that creates and displays the GUI when it is executes as a standalone application.'(http://pyqt.sourceforge.net/Docs/PyQt5/designer.html) 我得到的结果是

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(70, 50, 75, 23))
        self.pushButton.setObjectName("pushButton")

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

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


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

具有不同的主要功能。其余代码为 equivalent.

在 PyQt5 中,QApplication 方法不支持与 QtGui 一起使用,而是可以与 QtWidgets 一起使用。尝试像

这样重写你的代码
app = QtWidgets.QApplication(sys.argv)

如果使用 PyQt5 而不是 PyQt4。它应该可以工作。 我知道 QStyleFactory 等其他属性也已更改为与 QtWidgets 一起使用。

希望这可以解决您的问题。