1

This question has been asked a thousand times, and I do apologize for the repetition however it's evident to me I am missing a fundamental piece of this puzzle.

I've got a pretty standard iterative qtbutton setup:

for i, button in enumerate(qtbuttons):
    button.clicked.connect(lambda i=i: doTheThing(i))

def doTheThing(index):
    print("Button pushed has index %s"%index)

My understanding was that by doing lambda i=i:, the lambda would retain the index at the time it was assigned, thereby preventing all buttons from returning the last index. What I ended up with was the exact opposite issue. All buttons now return "0".

I also tried string formatting, something pointed to me in another thread, which did not work either.

I was working off of the info in this thread Python's lambda iteration not working as intended which is now 10 years old.

If possible, I'd really like to know:

  1. Why this is returning "0" for each button.
  2. How to achieve the desired behavior.
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    I suggest you use `lambda k=i: doTheThing(k)` - using `i` to represent two different variables is not likely to work and even if it does it will confuse the hell out of most people. – Joffan Apr 30 '21 at 15:43

1 Answers1

3

From https://doc.qt.io/qt-5/qabstractbutton.html#clicked:

void QAbstractButton::clicked(bool checked = false)

When clicked is emitted, it calls the connected function and passes the checked value to it.

Since your function has one optional parameter i, the checked value is bound as an argument to this parameter and if it is False (usually the case for normal push buttons), i appears as 0 (more info).

You need to pass a function that accepts two arguments; one is the checked value that is emitted from the signal, and the other one is i:

for i, button in enumerate(qtbuttons):
    button.clicked.connect(lambda checked, i=i: doTheThing(i))

The checked value can just be ignored by the function if it is not needed.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • This did the trick, thank you! When I did string formatting I saw the "False" and was very confused, this explains where it came from! – Timothy Chartier Apr 30 '21 at 16:11