#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
field = QtGui.QLineEdit("", self)
field.resize(field.sizeHint())
field.move(150, 100)
submit_button = QtGui.QPushButton("Fill hello world", self)
submit_button.resize(submit_button.sizeHint())
submit_button.move(50,300)
submit_button.clicked.connect(self.modify(field))
def modify(self, field):
field.setText("hello")
def main(): #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
field = QtGui.QLineEdit("", self)
field.resize(field.sizeHint())
field.move(150, 100)
submit_button = QtGui.QPushButton("Fill hello world", self)
submit_button.resize(submit_button.sizeHint())
submit_button.move(50,300)
submit_button.clicked.connect(self.modify(field))
def modify(self, field):
field.setText("hello")
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
好。所以这就是我想要做的。每当单击sumbit按钮时,我希望该字段由“ hello world”填充。
这意味着将提交按钮连接到用户定义的插槽。如何将字段传递给Modify()函数,在该函数中可以更改其文本?
目前,代码给出了错误:
File "test.py", line 21, in initUI
submit_button.clicked.connect(self.modify(field))
TypeError: connect() slot argument should be a callable or a signal, not 'NoneType'
最佳答案
首先,您从connect()
收到错误消息,因为您没有传递函数作为参数,而是传递了函数调用的结果,即None
。该行应写为:
submit_button.clicked.connect(self.modify)
然后,应更改修改功能以了解要填充的字段。实现此目的的一种方法是将字段保留在类变量中,并在其前面加上
self.
:#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
self.field = QtGui.QLineEdit("", self)
self.field.resize(self.field.sizeHint())
self.field.move(150, 100)
submit_button = QtGui.QPushButton("Fill hello world", self)
submit_button.resize(submit_button.sizeHint())
submit_button.move(50,300)
submit_button.clicked.connect(self.modify)
def modify(self):
self.field.setText("hello")
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()