在PyQt中创建和使用用户定义的槽

时间:2013-01-27 17:44:07

标签: python pyqt signals-slots

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

1 个答案:

答案 0 :(得分: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()