I have a working application. I added a menuBar() to the main window with some menus. Then, I hid it to free screen space. I wrote the code below so that when user presses ALT key, the menu bar appears if it's hidden, and it hides if it's displayed.
void MainWindow::keyPressEvent( QKeyEvent *k ) {
if(k->modifiers() & Qt::AltModifier) {
menuBar()->setHidden(!menuBar()->isHidden());
if(menuBar()->hasFocus()) {
QMessageBox::information(this, "Info", "Focus !");
}
}
}
As you can see, I also added a QMessageBox to see when the menuBar has the focus. And this box appears only half of the time. It goes like this :
- Application launched, menubar hidden
- I press ALT, menubar displayed, no message box, no focus
- I press ALT, menubar hidden
- I press ALT, menubar displayed, message box, focus
- I press ALT, menubar hidden
- I press ALT, menubar displayed, no message box, no focus
- I press ALT, menubar hidden
- I press ALT, menubar displayed, message box, focus
- etc.
How to make sure when the menuBar is displayed, it always has focus ?
I wanted to do the same thing. My solution, complete example, as a gist:
https://gist.github.com/xim/ee56564f425151ea2fa70f730d644873
Tested against Qt 5.9.4.
As it contains a lot of other junk, a minimal example:
Have you tried just adding the
setFocus
command?