Showing a popup menu on QGraphicsScene click or right click

TudorT picture TudorT · May 26, 2012 · Viewed 11.1k times · Source

Is there a way to show a popup when the user right clicks on an empty portion of the scene?

I'm new at Qt and I've tried slots and subclassing, but to no avail.

No such slot and, respectively:

"error: 'QMouseEvent' has not been declared"

when trying to implement the onMouseRelease event.

Answer

user362638 picture user362638 · May 26, 2012

QGraphicsView is the widget used for displaying the contents of the QGraphicsScene. So the correct place to implement the context menu (popup menu) is the QGraphicsView.

You need to reimplement the contextMenuEvent function is your own class inherited from QGraphicsView:

void YourGraphicsView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    menu.addAction(...);
    menu.addAction(...);
    ...
    menu.exec(event->globalPos());
}

See also the Qt's Menus Example.