PDA

View Full Version : Popup menu for a QGraphicsItem?



Morea
14th January 2007, 12:41
I have a class X that is a subclass of QGraphicsRectItem and I wiish to have a popup menu if the item is clicked with the right mouse button..

I'm not quite sure on how to do this.

void X::contextMenuEvent(QGraphicsSceneContextMenuEvent * event)
{
// if this is the proper way, how do I create a menu here
}

And is it defined somewhere that a rightclick generates a QGraphicsSceneContextMenuEvent ?
Or should I write code in the MousePressEvent() handler?

Anyway I would really like to know how to create the popup for the QGraphicsItem.

Morea
14th January 2007, 12:54
I think I've found the problem I had. A QGraphicsItem is not a QWidget, so it seems to work now. Therefor I change the question to: what is the difference between synchronously and asynchronously execution?

Bitto
18th January 2007, 18:33
A synchronous menu call, like QMenu::exec(), enters a modal event loop, and provides easy-to-read code like in the following example:



void MyItem::contextMenuEvent(QGraphicsSceneContextMenu Event *event)
{
QMenu menu;
menu.addAction("Action 1");
menu.addAction("Action 2");
QAction *a = menu.exec(event->screenPos());
qDebug("User clicked %s", qPrintable(a->text()));
}


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::popup(), does not reenter the event loop. Instead, you can deliver the results from the menu invocation to a slot in a QObject subclass.



void MyItem::contextMenuEvent(QGraphicsSceneContextMenu Event *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 *)));
}

Morea
4th February 2009, 21:18
What is the difference between contextMenuEvent and handling mousepressEvent and checking if the rightbutton was clicked?

jpn
4th February 2009, 21:27
From QContextMenuEvent docs:

Context menu events are sent to widgets when a user performs an action associated with opening a context menu. The actions required to open context menus vary between platforms; for example, on Windows, pressing the menu button or clicking the right mouse button will cause this event to be sent.