Qt responds to keyPressEvent in a child QWidget

I have a class based on QWidget 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 a 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 keyPressEvent in my tetris_canvas widget to respond to a keystroke?

I draw inside this canvas, and I need to respond to keystrokes so that the user can interact with things on this canvas.

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

+6
source share
1 answer

QWidget::keyPressEvent says the following:

The widget must call setFocusPolicy() to first take focus and focus in order to receive a keypress event.

So you have to do it. (Since you are not showing your constructors, I assume you skipped this part.)

Also the line after that says:

If you override this handler, it is very important that you call the base class implementation if you are not acting on the key.

You miss this in your widgets, but do it in your main window. Make sure you do this in both places.

+9
source

Source: https://habr.com/ru/post/899979/


All Articles