【发布时间】:2011-12-14 07:54:31
【问题描述】:
我有一个这样的 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);
}
我的问题是,如何让我的 tetris_canvas 小部件中的 keyPressEvent 响应按键?
我在该画布内绘图,我需要响应按键,以便用户可以与该画布上的事物进行交互。
小部件被添加到 ctor 中的 QGridLayout 或我的 main_window 类中。
【问题讨论】: