In Qt, how do I show keyboard shortcuts in a menu, but disable them?

I add a bunch QActionto my main windows. These actions can also be launched from the keyboard, and I want the shortcut to be visible in the menu, as usual, for example.

-----------------
|Copy     Ctrl+C|
-----------------

I can do it using QAction.setShortcut(). However, I do not want these QActiontriggered by shortcuts; I process all keyboard input separately in another place.

Is it possible? Can I disable the shortcut in QAction, but still have the shortcut text (in this example Ctrl+ C) in my menus?

EDIT . The way I finished it - it's connection to the events menu, aboutToShow()and aboutToHide()power on / off labels that they are only active when a menu is displayed. But I would appreciate a cleaner solution ...

+5
source share
2 answers

You can inherit from QAction and override QAction :: event (QEvent *):

class TriggerlessShortcutAction : public QAction
{
public:
    ...ctors...

protected:
    virtual bool event(QEvent* e)
    {
        if (e->type() == QEvent::Shortcut)
            return true;
        else
            return QAction::event(e);
    }
};

This will trigger any QEvent :: Shortcut type events dispatched to your actions so as not to trigger triggered () signals.

+8
source
action.setText("Copy\tCtrl+C");

It will look like a shortcut action, but the shortcut is not actually set.

Here is a complete example:

#include <QtGui>

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QMainWindow win;

    QMenu *menu = win.menuBar()->addMenu("Test");

    // This action will show Ctrl+T but will not trigger when Ctrl+T is typed.
    QAction *testAction = new QAction("Test\tCtrl+T", &win);
    app.connect(testAction, SIGNAL(triggered(bool)), SLOT(quit()));
    menu->addAction(testAction);

    // This action will show Ctrl+K and will trigger when Ctrl+K is typed.
    QAction *quitAction = new QAction("Quit", &win);
    quitAction->setShortcut(Qt::ControlModifier + Qt::Key_K);
    app.connect(quitAction, SIGNAL(triggered(bool)), SLOT(quit()));
    menu->addAction(quitAction);

    win.show();

    return app.exec();
}
+4
source

All Articles