Setting a mousePressEvent handler in a QTableWidgetItem

402 views Asked by At

I have a QTableWidget populated with several QTableWidgetItem objects. I am trying to add a mousePressEvent listener to my QTableWidget objects.

My current code is simple:

class TaskCell(QTableWidgetItem):
    def __init__(self, text, parent):
        super().__init__(text)
        self.parent = parent

    def mousePressEvent(self, event):
        print("Mouse clicked on cell with parent" + self.parent.id)

This to me seems rather straight-forward but unfortunately is not working. Can I not add a mousePressEvent to QTableWidgetItem objects? Thank you kindly.

1

There are 1 answers

0
eyllanesc On BEST ANSWER

QTableWidgetItem is not a visual element but an information container so it does not have a method similar to mousePressEvent. What to do is override the mousePressEvent method of the QTableWidget and get the TaskCells:

class TableWidget(QtWidgets.QTableWidget):
    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        item = self.itemAt(event.pos())
        if isinstance(item, TaskCell):
            print("Mouse clicked on cell with parent {}".format(item.parent.id))