从for循环中捕获变量,以供以后在QPushButton中使用 [英] Capture variable from for-loop for using later in QPushButton
问题描述
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 :))
当我在for循环中创建一个lambda
来从块的范围访问数据时,由于Python捕获工作的方式,我得到一个pylint
警告(cell-var-from-loop
).例如:
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)
还有更多类似的问题,但我现在仍然不知道如何系统地解决此问题.我尝试为lambda
提供默认值,例如建议的此处:
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)
但是当我这样做时,会发生奇怪的事情-在示例中value
应该是字符串,而show_data
是用bool
调用的.
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?
推荐答案
点击的信号发送一个选中的参数.因此,尝试:
The clicked signal sends a checked parameter. So try:
button.clicked.connect(lambda chk, v=value: show_data(v))
这篇关于从for循环中捕获变量,以供以后在QPushButton中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!