Nominate our 2022 Qt Champions!

keyPressEvent() isn't being called

  • In my main.cpp I declare a MainWindow object, and show it:

    MainWindow mainWindow;

    This object is a screen with 4 buttons (say screen 1). I connected the buttons with the Enter key so once clicked they open a new screen (2):

    connect(buttons[0], SIGNAL (released()), this, SLOT (openExample()));

    In that new screen I can either press ESC and return to the previous screen (which works by using installEventFilter() and implementing eventFilter()), or press ENT and go to the next new screen (3).

    That last thing is not working for me (pressing ENT in screen 2 to go to screen 3).

    This is what I've done:

    Screen 3:

    ExampleSettings::ExampleSettings(QWidget *parent)
                    : Settings(parent)
        QVBoxLayout* exampleSettingsLayout = new QVBoxLayout(&widget);
        for(int i=0; i<BUTTONS_NUMBER; i++)
            buttons[i] = new QLabel();
        buttons[0]->setText(tr("SETTING 1"));
        buttons[1]->setText(tr("SETTING 2"));
        for(int i=0; i<BUTTONS_NUMBER; i++)

    and declared keyPressEvent():

        void keyPressEvent(QKeyEvent *event);

    and defined it:

    void ExampleSettings::keyPressEvent(QKeyEvent *event)
        cout << "got event!" << endl;

    but it's not being called.

    I think the problem is in installing the event filter. Maybe because exampleSettingsLayout is dead after the constructor finishes? but I also tried to make it a member variable of the class, and it didn't work (keyPressEvent() still not called).

    I also tried eventFilter() instead of keyPressEvent(), but also this one isn't invoked.

  • Lifetime Qt Champion


    It's uncommon to install an event filter on a layout. It's the widgets that usually get keyboard focus thus the key related events.

  • This post is deleted!

  • @SGaist

    I see.
    Indeed widget.installEventFilter(this); worked, but with eventFilter() and not keyPressEvent().
    I don't understand how eventFilter() is activated and the condition if (event->type() == QEvent::KeyPress) is met, but on the other hand keyPressEvent() isn't invoked.
    The disadvantage with eventFilter() is that it's always triggered. Can anything be done to trigger only keyPressEvent()?

  • Lifetime Qt Champion

    Well, that's the use of eventFilter. In your reimplementation, you check only for what you are interested in and when it's not just call the base class implementation.

Log in to reply