How to trigger QMenuBar shortcuts from a child window
-
My application occasionally has a separate QOpenGLWindow showing. When this QOpenGLWindow is active/focused, the keyboard shortcuts in the QMenuBar belonging to the QMainWindow aren't triggered and I'd like them to be.
I've tried a number of combinations of eventFilters and QApplication::sendEvent() and haven't gotten anywhere. I also haven't managed to find a solution through searching. How can I do this correctly?
-
Hi
I cant promise its the "right way" but fast test showed it did work fine.
we use a QShortcut with setContext(Qt::ApplicationShortcut); to allow triggering the
action even then the QOpenGLWindow has focus.// this function replaces the QKeySequence with a // QShortcut that can application wise be activated. void MainWindow::MakeGlobal( QAction *theAction ) { // get actions key QKeySequence keys = theAction->shortcut(); //make new QShortcut *shortcut = new QShortcut( keys, this); // flag it as a global one shortcut->setContext(Qt::ApplicationShortcut); // let global trigger the action QObject::connect(shortcut, &QShortcut::activated, theAction, &QAction::trigger); } // test use. void MainWindow::on_pushButton_2_released() { MakeGlobal(ui->actionfire); // replace QOpenGLWidget *w = new QOpenGLWidget(); w->show(); }
having the QOpenGLWidget active and in front, still triggered the slot for the QMenu/action in
Mainwindow.Hope it can work for your use case too.
Note.
if i call
MakeGlobal(ui->actionfire);
from MainWindow constructor i get a warning.
"QAction::event: Ambiguous shortcut overload: Ctrl+F"
(which is correct ! :) and it wont trigger.
However, doing it just before showing other window, its does
work (also for main window) as long as other window is open.I think for a full solution, you must store the QKeySequence pr action and and clear the QKeySequence
on the action when you MakeGlobal ( to avoid Ambiguous shortcut )
and then when QOpenGLWindow closes, restore them back.
else there might be side effects. Such as when you close other window again, then it stops working.However, this solution suffer one thing as i can see.
While other Windows is open, mainwindow wont show the shortcut key on the menus.
If that is not acceptable, you should just ignore this post. :)Disclaimer. just proof of concept code. needs more love to fully work.