A synchronous menu call, like QMenu::exec(), enters a modal event loop, and provides easy-to-read code like in the following example:
{
menu.addAction("Action 1");
menu.addAction("Action 2");
QAction *a
= menu.
exec(event
->screenPos
());
qDebug("User clicked %s", qPrintable(a->text()));
}
void MyItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu menu;
menu.addAction("Action 1");
menu.addAction("Action 2");
QAction *a = menu.exec(event->screenPos());
qDebug("User clicked %s", qPrintable(a->text()));
}
To copy to clipboard, switch view to plain text mode
You can create the menu on the stack, and the result of the menu is available immediately. This is the preferred approach for QGraphicsItem. Beware, though, that because the event loop is completely reentered by the exec() call, arbitrary events will be processed, and this can lead to unexpected results (like how do you handle incoming network data while the popup menu is shown?).
An asynchronous call, like calling QMenu:
opup(), does not reenter the event loop. Instead, you can deliver the results from the menu invocation to a slot in a QObject subclass.
{
menu->addAction("Action 1");
menu->addAction("Action 2");
menu->popup(event->screenPos());
connect(menu,
SIGNAL(triggered
(QAction *)),
object,
SLOT(triggered
(QAction *)));
}
void MyItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu *menu = new QMenu;
menu->addAction("Action 1");
menu->addAction("Action 2");
menu->popup(event->screenPos());
connect(menu, SIGNAL(triggered(QAction *)),
object, SLOT(triggered(QAction *)));
}
To copy to clipboard, switch view to plain text mode
Bookmarks