Qt respond to keyPressEvent in child QWidget

10,024

The QWidget::keyPressEvent says this:

A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event.

So you should do that. (Since you're not showing your constructors, I'm guessing you missed that part.)

Also the line after that says:

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.

You're missing that in your widget, but doing it in your main window. Make sure you do it in both places.

Share:
10,024
Tony The Lion
Author by

Tony The Lion

#disgusted

Updated on June 04, 2022

Comments

  • Tony The Lion
    Tony The Lion about 2 years

    I have a QWidget derived class as such:

    class tetris_canvas : public QWidget
    {
        Q_OBJECT
    
    public:
        tetris_canvas(QWidget * parent = 0);
        ~tetris_canvas();
    
    protected:
        void paintEvent(QPaintEvent *event);
        void keyPressEvent(QKeyEvent *event);
    };
    
    //Never hits this keyPressEvent!!!
    void tetris_canvas::keyPressEvent(QKeyEvent * event)
    {
        if (event->key() == Qt::Key_Down)
        {
            rect->moveBottom(20);
            update();
        }
    }
    

    Then I have my main_window class:

    class main_window : public QWidget
    {
        Q_OBJECT
    
    public:
        main_window(QWidget* parent = 0, Qt::WFlags flags = 0);
        ~main_window();
    
    protected:
        void keyPressEvent(QKeyEvent * event);
    };
    
    //This keyPressEvent is hit!
    void main_window::keyPressEvent(QKeyEvent* event)
    {
        if (event->key() == Qt::Key_Escape)
        {
            QApplication::exit(0);
        }
        QWidget::keyPressEvent(event);
    }
    

    My question is, how do I get the keyPressEvent in my tetris_canvas widget to respond to a key press?

    I am drawing inside that canvas and I need to respond to keypresses so the user can interact with things on that canvas.

    The widget is added to a QGridLayout in the ctor or my main_window class.