Qt-使用Lambda将插槽与参数连接 [英] Qt - Connect slot with argument using lambda

查看:274
本文介绍了Qt-使用Lambda将插槽与参数连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个小部件,这些小部件将连接到需要额外参数的单个函数.

I have a couple of widgets that will be connected to a single function which required extra arguments.

我发现我可以在适当的地方使用lambda函数来传递该函数一些参数.

I found that I can use a lambda function in place to pass the function some arguments.

问题在于循环中的参数已被替换,而lambda函数仅传递最后一组参数.

The problem is the arguments are getting replaced in the loop and the lambda function is passing only the last one set.

这是我得到的:

self.widgets 是带有一组按键的字典,简而言之,我们假设它有2个按键[QToolButton],它们链接到它们的按键:播放"和停止"

self.widgets is a dictinary with keys for the group of buttons, to make it short let's say it have 2 buttons[QToolButton], linked to their keys: 'play' and 'stop'.

def connections(self):
    for group in self.widgets:
        self.widgets[group].clicked.connect(lambda: self.openMenu(group))

    def openMenu(self,group):
        print group

但是无论我单击哪个按钮,它都将始终打印相同的组,最后一个在for循环中进行迭代.

But no matter what button I click, it will always print the same group, the last that was iterate in the for loop.

有什么办法解决这个问题?

Any way to fix this?

推荐答案

问题是python的范围规则&关闭.您需要capture该组:

The issue is python's scoping rules & closures. You need to capture the group:

def connections(self):
    for group in self.widgets:
        self.widgets[group].clicked.connect(lambda g=group: self.openMenu(g))

    def openMenu(self,group):
        print(group)

这篇关于Qt-使用Lambda将插槽与参数连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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