Managing Alt key press/release events between a menubar and widget
-
The mainwindow of my application has a menubar and a central widget in it. There is an event filter installed on my central widget that is being used to bring in different behaviour on some special key press/release events.
I am trying to have something similar in case of an Alt Key press/release events.
But in case of an Alt key press, the focus gets transferred to the menu bar of my widget and the alt key release event is not received by my widgets event filter.
Here is a short code to demonstrate the issue:
class MyTextEdit: public QPlainTextEdit { public: MyTextEdit( QWidget * inParent ): QPlainTextEdit( inParent ) { installEventFilter( this ); setAutoFillBackground(true); } bool eventFilter( QObject * /*inObject*/, QEvent * inEvent ) { switch( inEvent->type() ) { case QEvent::KeyPress: if( static_cast< QKeyEvent * >( inEvent )->key() == Qt::Key_Alt ) { setStyleSheet("background-color:black;"); } break; case QEvent::KeyRelease: if( static_cast< QKeyEvent * >( inEvent )->key() == Qt::Key_Alt ) { setStyleSheet("background-color:white;"); } break; } return QPlainTextEdit::event( inEvent ); } }; class MyMenuBar: public QMenuBar { public: MyMenuBar( QWidget * inParent ): QMenuBar( inParent ) { addMenu( "File" ); } void keyPressEvent( QKeyEvent * inKeyEvent ) { if( inKeyEvent->key() == Qt::Key_Alt ) qDebug()<<"MyMenuBar: AltKey Press"; } void keyReleaseEvent( QKeyEvent * inKeyEvent ) { if( inKeyEvent->key() == Qt::Key_Alt ) qDebug()<<"MyMenuBar: AltKey Release"; } }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setMenuBar( new MyMenuBar( this ) ); setCentralWidget( new MyTextEdit( this ) ); }
If I run this code:
On pressing alt: my text edit background color changes to black.
On releasing alt: the background color stays as black. Release event goes to menubar
Would it be possible to have the focus go to the menu bar but to get the release event on the MyTextEditWidget as well.
That is, I want to let the user navigate the menu bar with alt key press, but I should be able to detect the key release in my central widget(MyTextEdit) even when the focus is on the menubar.
Is there any other way, than to install the textedit's event filter as the event filter for the menubar?
-
Hi,
Are you using accelerators in your menu bar ?
-
-
Alt or AltGr ?