How to disable Qt behavior on Linux to capture arrow keys to navigate widget focus

I work on a Qt application that is mainly developed on MacOS, but then it is also built and tested on Linux.

We define the keyPressEvent () method in our main window class to respond to certain keyboard events. In particular, we respond to Qt :: Key_Left, Qt :: Key_Right and Qt :: Key_Space. This works great on macOS. However, on Linux, we never get these events.

Performing some actions on Google (and confirming this with our Linux application behavior), it seems that the reason for this is because Qt uses these keys to navigate the keyboard of button widgets in the application’s GUI. If I press the arrow keys on Linux, I look at all the active button widgets, each time selecting them one by one. If I press the spacebar, the selected button is pressed.

All I have been able to find so far in Googling are suggestions on how to subclass or apply filters to certain buttons to avoid this behavior if the button ignores the event and passes it. But I do not want to do this for every button widget that I have ever added to my GUI. It is just lame.

Is there a way to disable this behavior globally and let my application code actually get ALL of the arrow keys and spaces?

+4
source share
1 answer

You can install the add global event listener to catch these events.

In the window constructor:

QApplication::instance()->installEventFilter(this); 

In the eventFilter window method:

 bool MainWindow::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent* key_event = static_cast<QKeyEvent*>(event); qDebug() << "key" << key_event->key() << "object" << object; //... } return false; } 

If you handled the event, you should return true from this function. You can use the object variable to find out the source of the event. For example, it could be some QPushButton. You can check if this button is a child of your main window, if necessary (if you have several top windows).

Another way is to completely turn off focus for the buttons. Set the focusPolicy buttons to NoFocus . Then they will not catch key events.

You can also subclass QPushButton and reimplement keyPressEvent with an empty implementation.

+2
source

All Articles