Essentially, I am trying to dynamically allocate a function to the clicked trigger of a push button. This is not working, and I am wondering how I should do this, if there is a way. My stripped down code:
DATA = [2, 3, 5, 1]
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.view = QTableWidget()
self.view.setRowCount(len(DATA))
self.view.setColumnCount(1)
self.view.setHorizontalHeaderLabels(["Function Name"])
for index, value in enumerate(DATA):
button = QPushButton(str(value))
button.clicked.connect(lambda: print(index))
self.view.setCellWidget(index, 0, button)
self.setCentralWidget(self.view)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
This code prints '3' when any button is pressed, whereas I want it to print '0' for the first button, '1' for the second etc. Can anyone tell me how to do this?
N.B. I have also tried methods defaulting the value of the lambda, for instance button.clicked.connect(lambda index=index: print(index))
but to no avail.