Search code examples
qtfocuskeyboard-eventsqwidget

Qt : keyboard focus


I am writing a program in Qt that looks like this:

Screen Capture

The main window is my class Window : QWidget, it has a QGridLayout containing four other widgets (Input_Menu : QWidget and Output_Menu : QWidget, and then two Canvas : QWidget)

I would like to trigger certain events when the user strikes a key. The problem is, the Window sometimes loses focus (it goes, say to Input_Menu, or maybe a button in Input_Menu...)

I have tried the following solutions, but they seem unsatisfactory (and dirty):

  1. Give Window the focus whenever it loses it.
  2. Tell each widget who could have the focus to trigger Window's KeyPressEvent function (or a clone of it) whenever it receives a keyboard event.

Ideally, I would like that if a widget receives an event (say a keyboard event) and doesn't know what to do with it, it should automatically call its parent's event handler. I would have hoped this to be a default feature of Qt but it doesn't look like it. On the other hand I am really confused about the whole focus thing, I don't really get what's going on. Can someone explain this to me: I have included a std::cout << "key pressed" << std::endl; in my Window::KeyPressEvent function. When I first run my program, it seems the focus is on the top QComboBox in Input_Menu: if I hit the Up/Down keys, I navigate in that box and no "key pressed" is showed in my console. If I hit most letters, nothing happens. But if I hit Left/Right keys, I do get a "key pressed" in my console!?

Thanks a lot in advance for your insights.


Solution

  • Actually, I found that for keys that are modifiers (such as Shift, Control), Qt supports finding out whether they are pressed.

    Eg : if(QApplication::keyboardModifiers() == Qt::ShiftModifier) ...

    This is good enough.