Capture variable from for-loop for using later in

2019-02-19 08:16发布

问题:

This question already has an answer here:

  • Using lambda expression to connect slots in pyqt 3 answers

Disclaimer: I've read other questions like this already (eg. this one) but didn't find a working solution for me yet (or I just don't understand them :))

When I create a lambda inside a for loop accessing data from the scope of the block I get a pylint warning (cell-var-from-loop) because of the way Python captures work. E.g:

for key, value in data.items():
    button = QtGui.QPushButton('show data')
    button.clicked.connect(lambda: show_data(value))
    table_widget.setCellWidget(1, 1, button)

There are more questions like this but I still don't now how I systematically solve this issue. I tried to provide default values to the lambda like suggested here:

for key, value in data.items():
    button = QtGui.QPushButton('show data')
    button.clicked.connect(lambda v=value: show_data(v))
    table_widget.setCellWidget(1, 1, button)

But when I do it like this weird things happen - while value ought to be a string in my example show_data is being called with a bool.

Am I doing something totally wrong? Should this approach work?

回答1:

The clicked signal sends a checked parameter. So try:

button.clicked.connect(lambda chk, v=value: show_data(v))