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

Shortcut for QAction without QMenuBar



  • Isn't it possible to define a shortcut for a QAction which is part of a QMenu but not added to a QMenuBar. I tried to set the context to ApplicationShortcut but the action seems not to get triggered.

    Thanks!


  • Lifetime Qt Champion

    Hi,

    What is the shortcut ?



  • I the case I tested it was Ctrl + H


  • Lifetime Qt Champion

    Can you show the code where you setup your action ?



  • @
    m_ActionHistory = new QAction(tr("History"), this);
    m_ActionHistory->setStatusTip(tr("History"));
    m_ActionHistory->setShortcut(Qt::CTRL + Qt::Key_H);
    m_ActionHistory->setShortcutContext(Qt::ApplicationShortcut);
    connect(m_ActionHistory, SIGNAL(triggered()), this, SIGNAL(OnHistory()));
    @


  • Lifetime Qt Champion

    I meant the complete setup, with this there's no information about whether you do it in a QWidget, I a custom QMenu etc.



  • The action is added to a QMenu with parent this (where this is among others a QWidget). This QMenu normally is shown on right click (customContextMenuRequested) and the click on the menu entry triggers the slot. The menu is created once and not deleted until the end of life of the QWidget.

    Any further information needed?



  • it sounds like you're creating the action inside the customContextMenu setup. that way, I think the shortcut is only valid while the context menu is active. try creating the action outside of the context menu setup



  • No, the menu and the action is created during the initialization. All of them i. e. the QMenu and the QAction are class members. In the slot which is called from the customContextMenuRequested only the QMenu::exec is called anymore.



  • Ok, I haven't actually tried giving QAction a shorcut key sequence so I can't really help you with that. How about this?

    @
    QShortcut * shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_M), this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(showMinimized()));
    @
    I use this kind of shortcut directly connected to the class.



  • The problem is that I don't want to have a bunch of shortcut objects around as I think that QAction should actually handle this. Also another connect is needed then.



  • And the second problem is, that the menu entry of course does not show the shortcut. Is that somehow possible to achieve?


Log in to reply