Search code examples
c++qtqgraphicssceneqmenuqaction

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?


Solution

  • I solved it by adding the QAction to the QGraphicsView parent of the QGraphicsScene.