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

Adding a shortcut to QAction inside QGraphicsScene context menu



  • My QGraphicsScene subclass WorkspaceScene contains a variable for each action that it later uses inside the context menu. I have a function that sets up the actions and adds the shortcuts (which is called in the constructor of the class), and then I have a function that creates the context menu, which is called in the contextMenuEvent function I reimplemented.

    Here's some relevant code:

    // Constructor
    WorkspaceScene::WorkspaceScene()
    {
        _setUpActions();
    }
    
    // ContextMenuEvent
    void WorkspaceScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
    {
        _setUpItemMenu();
        _itemContextMenu.exec(event->screenPos());
    }
    
    void WorkspaceScene::_setUpActions()
    {
        deleteAction = new QAction("Delete");
        deleteAction->setShortcut(QKeySequence::Delete); // This should add the shortcut
        connect(deleteAction, &QAction::triggered, this, &WorkspaceScene::deleteItemSlot);
    }
    
    void WorkspaceScene::_setUpItemMenu()
    {
        _itemContextMenu.clear();
        _itemContextMenu.addAction(deleteAction);
    }
    

    This successfully sets up the actions and they work inside the context menu but the shortcut doesn't seem to work. What's the correct way of doing this?


  • Lifetime Qt Champion

    In that case you need to also add the action to the widget.


  • Lifetime Qt Champion

    Hi,

    Do you mean you want the action to be triggered by the delete key when the menu is opened ? Or also the rest of the time ?



  • This post is deleted!


  • @SGaist I'd like the action to be triggerred at any point (even if the menu is not opened)


  • Lifetime Qt Champion

    In that case you need to also add the action to the widget.



  • @SGaist That made it work. Thanks!


Log in to reply