6
我有一個QWidget派生類這樣:Qt來keyPressEvent應對兒童QWidget的
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();
}
}
然後,我有我的main_window類:
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);
}
我的問題是,我該如何得到keyPressEvent
在我的tetris_canvas
小部件中響應按鍵?
我正在繪製該畫布,我需要響應按鍵,以便用戶可以與該畫布上的事物進行交互。
小部件被添加到ctor中的QGridLayout
或我的main_window
類中。