2

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?

f.rodrigues
  • 3,499
  • 6
  • 26
  • 62
  • 1
    possible duplicate of [PyQt connect inside for loop vs. separate calls results in different behavior](http://stackoverflow.com/questions/27208706/pyqt-connect-inside-for-loop-vs-separate-calls-results-in-different-behavior) – three_pineapples Dec 03 '14 at 02:26

1 Answers1

7

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)
Gerrat
  • 28,863
  • 9
  • 73
  • 101