Solved How to have QWidget keypress override main window menu shortcuts?
-
I'm writing a program where I'd like to have a custom widget override the keypress behavior of the main menu actions.
When it program starts, it sets up it's main menu using QActions:
QMenuBar* mb = new QMenuBar(); QMenu* editMenu = mb->addMenu(tr("&Edit")); { QAction* action = new QAction(tr("&Delete"), _mainWindow); action->setShortcut(QKeySequence("Delete")); action->setStatusTip(tr("Delete selection")); connect(action, &QAction::triggered, this, &Environment::deleteSelection); actionMap[ACTION_DELETE] = action; editMenu->addAction(actionMap[ACTION_DELETE]); } //More entries like this _mainWindow->setMenuBar(mb);
My custom widget needs to do something different when Delete is pressed. I've overridden keyPressEvent, and while keyPressEvent is being called for most keypresses, any key combo that the maim menu actions have been assigned to is not making it into this method. Is there any way to have my widget handle the keypress first, and then only pass it on to the main window if it decides it doesn't need it?
void CurvesEditor::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Delete: { //Deletion code return; } } QWidget::keyPressEvent(event); }
-
In your widget override event(), check event type() and handle QEvent::ShortcutOverride to accept the event when the key sequence is
QKeySequence::Delete
. -
This post is deleted! -
That worked. Thanks!