[Solved] Context menu in QGraphicsScene and QGraphicsItem
-
I am trying to understand what the better approach is: To implement the context menu in the QGraphicsScene and using type information to figure out which one is the proper context menu to be displayed (because they vary from the type of item in my case) or whether I should implement the context menu directly in the QGraphicsItem.
The issue I see with implementing it in item itself is that I would need to inherit from QGraphicsObject instead because I would need to have access to the signal & slot concept to notify the rest of the world when eg. the item was deleted using the items context menu.
Any tips?
-
You don't have to inherit QGraphicsObject to have a context menu. See contextMenuEvent for an example.
-
@Chris-Kawa I agree. What I mean is that I would need to inherit from
QGraphicsObject
in order to have a signal in my graphics item that would allow to tell the rest of the world that something changed (eg. that the item was deleted using the items context menu). -
I guess it depends on how you want to design your system. The two mentioned approaches both seem correct:
- item is "self aware". It has a context menu that allows it to delete itself. If it's supposed to communicate to others about its state it seems natural that it would be a QObject, thus inheriting from QGraphicsObject. This self-awareness costs the overhead of being a QObject. Is it worth it - something you would have to measure and decide for your case.
- the scene manages the items and informs others about items state via signals. In that case the scene would have to have "intimate knowledge" about its items to adjust the contents of the menu.
When making a decission I would consider what is going to be connected to those menu signals. If it's like a generic thing that would handle the change in any item then the second solution might be better as you could connect just once to a
YourScene::someItemStateChanged(QGraphicsItem* item)
and be done with it. If the "observer" is interested in particular items the first approach seems better fitted, as you could connect directly to only those items of interest and don't mind others.Apart from that it's a decision of balance - what's more important to you - that the items are lean and mean or that they are hermetic from the scene. I think there's no "one size fits all" answer to that.
-
Thank you for your detailed answer. I know where to go from here.