我正在制作一个只包含按钮的简单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
答案 0 :(得分: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_())