0

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.

Alice F
  • 435
  • 5
  • 13
  • This does not answer my question, no. This simply outputs 'False' instead of an index. – Alice F Jan 10 '21 at 13:03
  • use `button.clicked.connect(lambda checked, index=index: print(index))` – eyllanesc Jan 10 '21 at 13:32
  • @OliverF read the [`clicked()`](https://doc.qt.io/qt-5/qabstractbutton.html#clicked) signal documentation: it always sends a `checked` argument (which is always False for non checkable buttons), so you need to provide an *extra* keyword argument to the lambda as eyllanesc shows. – musicamante Jan 10 '21 at 13:57

0 Answers0