I'm trying to connect a function to buttons created inside a loop, with a different argument for the function for each button. This is my attempt:
from PyQt5 import QtWidgets, QtGui, QtCore
class GUI(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
self.show()
for num in range(5):
b = QtWidgets.QPushButton(str(num))
string = f"You clicked button {num}!"
b.clicked.connect(lambda x=string: self.func(x))
layout.addWidget(b)
def func(self, thing):
print(thing)
app = QtWidgets.QApplication([])
win = GUI()
app.exec_()
This creates a GUI with 5 buttons, but clicking them just prints "False" to the console.
Initially I had connect(lambda: self.func(string))
which caused each button to print You clicked button 4!
because of this:
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
But I have no idea why it's now passing False. I tried using the same functions and logic outside of PyQt as below and that successfully printed 0 1 2 3 4 to the console.
func_list = []
for num in range(5):
func_list.append(lambda x=num: func(x))
def func(thing):
print(thing)
for f in func_list:
f()