1

我正在制作一个仅包含一个按钮的简单 GUI。我决定用 PyQt Designer 来做。

我决定 Designer 生成的 UI 将在一个文件中,其余的将在另一个导入 UI 的模块中。

PyQt Designer 生成的文件是:

from PyQt4 import QtCore, QtGui

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, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(326, 232)
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(104, 30, 101, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "PushButton", None))

导入它的主文件如下所示:

import sys
from PyQt4 import QtCore, QtGui
from stacko import Ui_Form

class test(Ui_Form):
    self.pushButton.connect.clicked(self.onClick)
    def onClick(self):
        print "clicked!"

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

我希望当点击按钮时它会打印出“点击!”。出于某种原因,它对我不起作用。我阅读了很多关于类/子类和 OOP 的内容,但我仍然无法让它工作。

它引发了一个错误:NameError: name 'self' is not defined

4

1 回答 1

2

这是您的主模块的外观:

import sys
from PyQt4 import QtCore, QtGui
from stacko import Ui_Form

class Test(QtGui.QWidget, Ui_Form):
    def __init__(self):
        super(Test, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.onClick)

    def onClick(self):
        print "clicked!"

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = Test()
    window.show()
    sys.exit(app.exec_())
于 2014-10-31T21:26:07.070 回答