如何将参数传递给 PyQt 中的回调函数 [英] How to pass arguments to callback functions in PyQt

查看:132
本文介绍了如何将参数传递给 PyQt 中的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have around 10 QAction (this number will vary in runtime) in a toolbar, which all will do same thing, but using different parameters. I am thinking to add parameter as an attribute to QAction object, and then, QAction's triggered signal will also send object's itself to the callback function, so that I could get required parameters for the function. I have actually 2 questions about this:

  • 能做到吗?
  • 有没有更好的方法来做到这一点?

推荐答案

您可以使用 信号映射器.但是,最好简单地发送一个标识符并在信号处理程序中完成所有工作.

You can send the action object itself using a signal mapper. However, it may be better to simply send an identifier and do all the work within the signal handler.

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

Here's a simple demo script:

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_())

这篇关于如何将参数传递给 PyQt 中的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆