qtdelegatescontextmenuqtableviewqmenu

Qt QTableView context menu and right selection


Hello I'm using a QTableView with custom item delegate.

I'm using editorEvent in the delegate to show a context menu which is different for each item that is right-clicked. The menu is displayed using QMenu::exec().

The problem is that when i right click on a non-selected cell, the menu is displayed (blocking) and only after the menu disappears the cell is selected. This is because mouse click is captured first by the delegate, and then propagated to the view to make the selection.

Which alternative/workaround might I try?

EDIT

I did catch QEvent::MouseButtonPress. Using MouseButtonRelease instead makes the cell be selected first and then the context appears, but if you move the mouse while having button pressed the selection remains where you pressed the button while the context menu appears for the cell where the button was released.

I think that the only way to fix this is moving this code out of the delegate as suggested below.


Solution

  • If you only need to show the menu when the user makes a right click then there's no need to create a custom item delegate.

    You can handle the mouseReleaseEvent when event->button() == Qt::RightButton and get the selected item using QTableView::selectionModel().

    Hope it helps.