How to add a Qpushbutton to Qtablewidget?

Asked

Viewed 75 times

0

I am creating an application in Pyqt5 with a table, using the classes QTableWidget and QTableWidgetItem. The table has three columns - the first two are just texts and the last one is a button, which will be used to remove the item from the table. My code below:

def set_items(self, data):
    self.table.setRowCount(len(data))
    self.table.setColumnCount(3)

    current_row = 0

    for title, info in data.items():
        button = QPushButton("Remove")
        button.clicked.connect(self.__remove_item)

        self.table.setItem(current_row, 0, QTableWidgetItem(title))
        self.table.setItem(current_row, 1, QTableWidgetItem(info))
        self.table.setItem(current_row, 2, QTableWidgetItem(button))
        current_row += 1

The problem is that I can’t add the button to the table because the following error is launched:

TypeError: arguments did not match any overloaded call:
  QTableWidgetItem(type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(str, type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(QIcon, str, type: int = QTableWidgetItem.ItemType.Type): argument 1 has unexpected type 'QPushButton'
  QTableWidgetItem(QTableWidgetItem): argument 1 has unexpected type 'QPushButton'

From the error message, you can see that the problem is in QTableWidgetItem not accept a QPushButton or any other widget other than str, int, QIcon or an instance of the same class. My question is: what should I do then to add a QPushButton or even another widget to the table?

1 answer

1


To add a widget to a QTableWidget, we use the method setCellWidget same. Try to change this line

self.table.setItem(current_row, 2, QTableWidgetItem(button))

for

self.table.setCellWidget(current_row, 2, button)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.