This issues is related to pyside(6). The following code should work, but I keep getting a single value 't' as the result when a button is clicked.
labels_list = ["y", "t", "u", "N", "T", "U"]
who_cb_list = []
for ii in range(6):
who_cb_list.append(qtw.QRadioButton())
who_cb_list[ii].setText(labels_list[ii])
who_cb_list[ii].clicked.connect(lambda ii=ii: self.setWho(labels_list[ii]))
Originally I made the mistake of
who_cb_list[ii].clicked.connect(lambda: self.setWho(labels_list[ii]))
When I clicked on the radio button of course I always connect the last value of the list ('U') on every button.
But the new way (lambda ii=ii:) still caused an error. Oddly I would always get 't'. I asked chatGPT and got this suggestion which worked.
def create_lambda_handler(label):
return lambda: self.setWho(label)
for ii, label in enumerate(labels_list):
who_cb_list.append(qtw.QRadioButton())
who_cb_list[ii].setText(label)
who_cb_list[ii].clicked.connect(create_lambda_handler(label))
The function defined outside the loop makes a closure.... Another way to do this turned out to be using func tools:
import functools
for ii, label in enumerate(labels_list):
who_cb_list.append(qtw.QRadioButton())
who_cb_list[ii].setText(label)
who_cb_list[ii].clicked.connect(functools.partial(self.setWho, label))
From chatGPT: functools.partial is a function in the Python standard library that allows you to create partial function application. It's a way to "freeze" some portion of a function's arguments, creating a new function with those arguments pre-filled.
user2390182 provided this link which explains all this: Common Gotchas — The Hitchhiker's Guide to Python
Here is the entire exchange with chatGPT https://chat.openai.com/share/afa29ada-e97d-476c-b67d-495f657d5278