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.
The
QWidget::keyPressEventsays this: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:
You’re missing that in your widget, but doing it in your main window. Make sure you do it in both places.