PDA

View Full Version : Context menus for GraphicsView and QGraphicsItem



anava
28th February 2016, 18:11
There is a GraphiscView widget in my dialog, and menu setup is looking:


m_ui->graphicsView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_ui->graphicsView, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(showContextMenu(const QPoint&)));


If I add an object of a class, derived from QGraphicsItem, and having this method overriden:


void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) Q_DECL_OVERRIDE;

, the graphicsView context menu is beig shown, if I right-click on it, not one of the item.
Item's menu is shown only if I comment out set up of graphicsView menu.

How to do it right way, that if I click on an item, its menu is shown, if on an empty field of graphicsView - the graphicsView's menu?

d_stranz
28th February 2016, 20:23
Look at the example code in QGraphicsView::itemAt(). You will need to implement something like that in your showContextMenu() slot - first check to see if there is an item at the QPoint. If there is, and it is one of your custom items, then you need to display its context menu (maybe send it a QGraphicsSceneContextMenuEvent). If there is nothing at the QPoint, then you display the QGraphicsView's context menu. The problem you are having is that the view's context menu handler is eating the right-clicks and your graphics items never see them.

anava
28th February 2016, 22:14
Thank you, d_stranz!
You mean, I should "propagate" this event myself, qt framework does not do it? Then a question: why to implement something concerning menu in the item? Maybe, if only graphicsview knows about this event, and it shows a menu, it should process the rest? I do not like it, but it seems, there is an unconvenient concept in the framework.

d_stranz
29th February 2016, 23:02
The QGraphicsItem is a child of the QGraphicsScene, not the QGraphicsView. Therefore, it has its own mechanism for handling context events. If you put the scene in a QGraphicsView that does not have custom context menus, then I think the QGraphicsItem context menus will work as you expect. If you put the same scene in a QGraphicsView that does have custom context menus, then the QGraphicsView context menu handling takes precedence.