1
votes

I am building a Qt application on Linux. I have a menu bar in the main window with two menus in it, each with several actions, all of which have keyboard shortcuts associated with them. The keyboard shortcuts work when the menus are not open, but when one of the menus is open, none of them work.

The shortcuts were added to the actions with setShortcut prior to the actions being added to their respective menus with [menuobject]->addAction. All the actions have the main window as their parent. After reading QAction shortcut doesnt always work I added calls to addAction, adding the action to the main window. This did not correct the problem.

Example of the code for one of the menu items:

//In the main window constructor
gameQuit = new QAction(QString(tr("&Quit\tCtrl+Q")), this);
gameQuit->setShortcut(QKeySequence(Qt::Key_Q | Qt::CTRL));
addAction(gameQuit);

connect(gameQuit, SIGNAL(triggered()), this, SLOT(close()));

gameMenu = menuBar()->addMenu(QString(tr("&Game")));
gameMenu->addAction(gameQuit);

In QtCreator, which I assume was written with Qt, the keyboard shortcuts for the menu items do work when the menus are open, so I think there must be a way.

Thanks for any help.

1
Why was this downvoted?rsood
My guess is this was because you did not provide a minimal example. On StackOverflow most questions require a small code example that shows the problem and that others can try.drescherjm
@drescherjm Hmm... didn't see that in the prepost guidelines. I'll keep it in mind for the future. Thanks.rsood

1 Answers

0
votes

Taking some advice from the comments of the cited post (which had been rebuked, which is why I didn't try it initially), I modified the shortcut context using [actionobject]->setShortcutContext(). Apparently the default does not work in my scenario.

I first tried setting to Qt::WindowShortcut, which didn't work. Qt::ApplicationShortcut did work, however, this may have shortcomings as noted in the comments of the cited post. They don't happen to matter for this particular application of mine though, so I am going to post and accept this as the answer.

Example of the correcting code:

//In the constructor of the main window, after creation of the action and 
//setting of the shortcut
gameQuit->setShortcutContext(Qt::ApplicationShortcut);