Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Different Context Menu for QGraphicsObject in QGraphicsScene



  • In creating a graphical editor, I have reimplemented QGraphicsScene. Part of this includes the definition of a context menu by reimplementing QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *). The code looks like this:

    void MyScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *Event) {
        // Create QActions
        // Connect signals
        QMenu *Menu = new QMenu;
        // Add actions to menu
        Menu->popup(Event->screenPos());
        Event->accept();
    }
    

    I also created a subclass of QGraphicsObject for drawing my graphics item. For this graphics item, I also want to have a context menu, but a different one. And I defined it by reimplementing QGraphicsObject::contextMenuEvent(QGraphicsSceneContextMenuEvent *). That code looks as follows

    void MyItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *Event) {
        // Create QActions
        // Connect Signals
        QMenu *Menu = new QMenu;
        // Add actions to menu
        Menu->popup(Event->screenPos());
        Event->accept();
    }
    

    Unfortunately, the context menu of MyItem does not show up when I right-click on the item in the scene. Instead it still shows the context menu of the scene. Any idea on how I can get the context menu of MyItem when I right-click on the item while having the scene context menu when right-clicking anywhere else?


  • Lifetime Qt Champion

    Hi,

    There was a mail sent to the interest mailing list mentioning this.

    You should check the provided workaround.

    Hope it helps



  • Great, this helped me to make it work. However, I do have another question now as I originally reimplemented QGraphicsScene instead of QGraphicsView. This solution assumes reimplementation of QGraphicsView. What is generally the best approach / the difference between the two approaches?


  • Lifetime Qt Champion

    The scene can be shared between several views which might not all be concerned by that menu.


Log in to reply