Reputation: 5153
I have a custom widget that extends QMainWindow
. There I am adding a number of QAction
s 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
}
Upvotes: 2
Views: 3016
Reputation: 318
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.
Upvotes: 6
Reputation: 32635
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);
Upvotes: 0