Search code examples
pythoneventspyqtmouseqtableview

PyQt: How to determine, which mouse button is pressed and over which QTableView's cell at the same time?


I write a PyQt application with QTableView, which should insert a new column in response to a left click and delete a column in response to right mouse click on its cells.

What signal should I connect handlers to? If I use QAbstractItemView.clicked, I can receive the index of column, but can't determine the mouse button, cause it doesn't receive the event.

One the other hand, if I use QAbstractScrollArea.mousePressEvent, I can get event.button(), but it's not clear, how to recover the cell's index.

Qt kinda remind of Schrödinger's indeterminacy here :)


Solution

  • You can get the state of the mouse buttons with QApplication.mouseButtons:

        buttons = QApplication.instance().mouseButtons()
    

    With mousePressEvent, you can use QAbstractItemView.indexAt to get the index:

        index = tableview.indexAt(event.pos())