Search code examples
pythonpysideqtablewidgetpyside6

Check if click is on cell or free space inside QTableWidget


There is a fixed size QTableWidget with some rows and columns, the rest of the QTableWidget is blank and unoccupied. If the users doubleclicks on a cell, a dialog should be displayed, if the user doubleclicks on a blank area of the QTableWidget, a new row should be appended to the table.

I tried to solve it like this:

class TableWidget(QTableWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.doubleClicked.connect(self.cellDoubleClicked)

    def cellDoubleClicked(self):
        # display dialog here # 

    def mouseDoubleClickEvent(self, event: QtGui.QMouseEvent) -> None:
        event.ignore()
        super().mouseDoubleClickEvent(event)
        if not event.isAccepted():
            # add row to table
        return

but as I found out, the event gets never accepted. I think I did something stupidly wrong here. Now mouseDoubleClickEvent's if gets called every doubleclick and cellDoubleClicked only if I doubleclick a cell. I tried to distinguish theses events by looking at currentIndex but that always points to the latest index selected, even after calling clearSelection. Is there an option to solve this based on my code stump or is it wrong all the way?


Solution

  • It's much easier than that: use indexAt(pos) which returns an invalid index if the position doesn't correspond to an existing item.

    class TableWidget(QTableWidget):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
        def mouseDoubleClickEvent(self, event: QtGui.QMouseEvent) -> None:
            super().mouseDoubleClickEvent(event)
            index = self.indexAt(event.pos())
            if index.isValid():
                # show dialog
            else:
                # add row to table