Qt adding non-menubar keyboard shortcut to QMainWindow

2.9k views Asked by At

I have a custom widget that extends QMainWindow. There I am adding a number of QActions to the menu bar, along with keyboard shortcuts for each, and they work fine. Now I want to remove some of those actions from the menubar, but I want to keep the shortcuts enabled (the user can know about the availability of the shortcuts from a Help dialog). So first I decided that I will make the actions invisible.

That did not work, so I guess the action cannot be invisible if the shortcuts have to work. So I added it to the main window, still they are not working. Any idea, how do I make it work? Here is my code. Whatever needs to happen is there in the method someMethod.

class MyWidget: public QMainWindow {
    public:
        MyWidget();

};

MyWidget::MyWidget() {
    QAction *myAct = new QAction(tr("&Some Text"), this);
    fNextmyActPageAct->setShortcut(QKeySequence(Qt::Key_Right));
    myAct->setVisible(false); //adding this does not work
    connect(myAct, SIGNAL(triggered()), this, SLOT(someMethod()));

    ...

    QMenu *someMenu = menuBar()->addMenu(tr("&Some Menu"));
    someMenu->addAction(myAct); //this works, the option shows up in the menu 'Some Menu' and the shortcut works
    this->addAction(myAct); //does not work

}
2

There are 2 answers

6
Nejat On

You can use QShortcut and pass the key, the target widget and the relevant slot as parameters to it's constructor. Just put this in the constructor of MyWidget :

QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_Right),this,SLOT(someMethod()));
shortcut->setAutoRepeat(false);
5
Ali Mofrad On

I tested this code and it's working fine :

QAction* myAct = new QAction(this);
myAct->setShortcut(Qt::Key_Right);
connect(myAct, SIGNAL(triggered()), this, SLOT(someMethod()));
this->addAction(myAct);

Do not add QAction to your menuBar.