Qt - Connect slot with argument using lambda

萝らか妹 提交于 2019-12-23 02:53:26

问题


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

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

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

Heres what I got:

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/27262288/qt-connect-slot-with-argument-using-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!