alez
alez

Reputation: 125

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.

Upvotes: 1

Views: 2280

Answers (3)

signedav
signedav

Reputation: 146

Worked like @alez suggested. To get the coordinates I used QTableView->mapToGlobal(pos)

Upvotes: 0

alez
alez

Reputation: 125

As suggested by cdonts using the delegate to show a context menu is not only not needed, but also not well performing.

What I have used is QWidget::setContextMenuPolicy(Qt::CustomContextMenu) and the signal QWidget::customContextMenuRequested(QPoint). This allows me to check actual selection asking the view its SelectionModel before creating the context menu (which could be done in the model to easily customize the menu and edit the data accordingly).

Remember to use QTableView->viewport()->maptoglobalpos(point) to obtain global coordinates at which the menu should appear.

Upvotes: 4

cdonts
cdonts

Reputation: 9599

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.

Upvotes: 3

Related Questions