AttributeError:'模块'对象没有属性' QtWidget'

时间:2015-04-18 05:19:51

标签: python pyqt5

我安装了PyQt5和Python3.4。 但是当我构建我的程序时,我收到了一条错误消息。

AttributeError:'module'对象没有属性'QtWidget'

我该如何解决这个问题?

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context,text)

class Ui_Form(QtGui.QtWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(Form)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.PrintHam_btn = QtWidgets.QPushButton(Form)
        self.PrintHam_btn.setObjectName("PrintHam_btn")
        self.horizontalLayout.addWidget(self.PrintHam_btn)
        self.horizontalLayout_2.addLayout(self.horizontalLayout)

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Super Ham"))
        self.PrintHam_btn.setText(_translate("Form", "Print Ham"))
        self.PrintHam_btn.clicked.connect(self.printHam)

    def printham(self):
        print ("Ham!")

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

这是我的代码。我不知道为什么说没有QtWidgets

2 个答案:

答案 0 :(得分:3)

您要犯的第一个错误是编辑pyuic编译的模块。永远不要这样做。始终将模块导入主应用程序,以便您可以在必要时重新编译它。

Qt4中QtGui模块中的许多类已移至Qt5中的QtWidgets模块。还有其他类(如QString)在PyQt5中不再可用。

看起来您的示例代码是使用pyuic4编译的,因此您无法将其与PyQt5一起使用。您需要使用pyuic5重新编译它。

(你的示例代码中也有一个拼写错误。没有QtWidget这样的类:你可能意味着QWidget。但修复它是不够的。你必须重新编译模块pyuic5解决所有问题。)

答案 1 :(得分:0)

我认为问题在于这一行:

class Ui_Form(QtGui.QtWidget):

你应该QtWidgetQWidget