connect() in for loop python 3.11
-
wrote on 8 May 2023, 20:42 last edited by
beginner here!
In my for loop I connect buttons to a common method using a lambda to pass a loop index .. when I click both buttons I see "1" printed; I expected to see "0" and "1" .. how do I change the code to get the expected results?
import sys from PyQt6 import QtWidgets class Foo(QtWidgets.QWidget): def __init__(self): super().__init__() self.layout = QtWidgets.QHBoxLayout() self.setLayout(self.layout) def setupUI(self): for index in range(2): button = QtWidgets.QPushButton(str(index)) button.clicked.connect(lambda: self.buttonClicked(index)) self.layout.addWidget(button) def buttonClicked(self, index): print(index) app = QtWidgets.QApplication(sys.argv) foo = Foo() foo.setupUI() foo.show() sys.exit(app.exec())
-
beginner here!
In my for loop I connect buttons to a common method using a lambda to pass a loop index .. when I click both buttons I see "1" printed; I expected to see "0" and "1" .. how do I change the code to get the expected results?
import sys from PyQt6 import QtWidgets class Foo(QtWidgets.QWidget): def __init__(self): super().__init__() self.layout = QtWidgets.QHBoxLayout() self.setLayout(self.layout) def setupUI(self): for index in range(2): button = QtWidgets.QPushButton(str(index)) button.clicked.connect(lambda: self.buttonClicked(index)) self.layout.addWidget(button) def buttonClicked(self, index): print(index) app = QtWidgets.QApplication(sys.argv) foo = Foo() foo.setupUI() foo.show() sys.exit(app.exec())
wrote on 8 May 2023, 21:54 last edited by -
1/2