1
#!/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'
4

1 回答 1

1

首先,您收到错误消息,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()
于 2013-01-27T21:51:21.563 回答