如何在PyQt中将参数传递给回调函数

时间:2012-01-11 18:03:22

标签: python pyqt signals-slots

我在工具栏中有大约10个QAction(这个数字在运行时会有所不同),它们都会做同样的事情,但使用不同的参数。我想将参数作为属性添加到QAction对象,然后,QAction的触发信号也会将对象本身发送到回调函数,这样我就可以得到函数所需的参数。我实际上有两个问题:

  • 可以吗?
  • 有更好的方法吗?

5 个答案:

答案 0 :(得分:41)

  

如何将参数传递给PyQt中的回调函数

您可以使用标准Python库中的functools.partialQAction的示例:

some_action.triggered.connect(functools.partial(some_callback, param1, param2))

答案 1 :(得分:9)

您可以使用与GUI控件槽相关联的lambda函数将额外的参数传递给您想要执行的方法。

# Create the build button with its caption
self.build_button = QPushButton('&Build Greeting', self)
# Connect the button's clicked signal to AddControl
self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
def AddControl(self, name):
    print name

来源:snip2code - Using Lambda Function To Pass Extra Argument in PyQt4

答案 2 :(得分:4)

您可以使用signal mapper发送操作对象本身。但是,简单地发送标识符并在信号处理程序中完成所有工作可能更好。

这是一个简单的演示脚本:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.mapper = QtCore.QSignalMapper(self)
        self.toolbar = self.addToolBar('Foo')
        self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
        for text in 'One Two Three'.split():
            action = QtGui.QAction(text, self)
            self.mapper.setMapping(action, text)
            action.triggered.connect(self.mapper.map)
            self.toolbar.addAction(action)
        self.mapper.mapped['QString'].connect(self.handleButton)
        self.edit = QtGui.QLineEdit(self)
        self.setCentralWidget(self.edit)

    def handleButton(self, identifier):
        if identifier == 'One':
            text = 'Do This'
        elif identifier == 'Two':
            text = 'Do That'
        elif identifier == 'Three':
            text = 'Do Other'
        self.edit.setText(text)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(300, 60)
    window.show()
    sys.exit(app.exec_())

答案 3 :(得分:3)

传递参数的最佳方法是根本不传递它们。您可以使用python的动态特性,并在窗口小部件本身上设置您需要的任何数据作为自己的属性,使用self.sender()在处理程序中获取目标窗口小部件,然后直接从窗口小部件获取所需的任何属性。

在此示例中,创建了五个按钮,并在按钮小部件上将所需状态设置为my_own_data属性:

import sys
from PyQt4 import QtGui, QtCore

class Main(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.centralwidget = QtGui.QWidget()
        self.vboxlayout = QtGui.QVBoxLayout()

        for idx in range(5):
            button = QtGui.QPushButton('button ' + str(idx), None)
            button.my_own_data = str(idx)  # <<< set your own property
            button.clicked.connect(self.click_handler)  # <<< no args needed
            self.vboxlayout.addWidget(button)

        self.centralwidget.setLayout(self.vboxlayout)
        self.setCentralWidget(self.centralwidget)
        self.show()

    def click_handler(self, data=None):
        if not data:
            target = self.sender()  # <<< get the event target, i.e. the button widget
            data = target.my_own_data  # <<< get your own property
        QtGui.QMessageBox.information(self, 
                                      "you clicked me!", 
                                      "my index is {0}".format(data))

app = QtGui.QApplication(sys.argv)
main = Main()
main.show()

sys.exit(app.exec_())

答案 4 :(得分:1)

PyQt使用QSignalMapper的方式仍然存在错误。我在这里发现了一个解决方法:

http://www.riverbankcomputing.com/pipermail/pyqt/2010-March/026113.html

要修复已回答的问题,请进行以下更改:

        action.triggered[()].connect(self.mapper.map)

以下版本的Python需要这样做:

Python 2.6.6 (r266:84292, Feb 21 2013, 19:26:11)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2