Qt 响应子 QWidget 中的 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);
}
我的问题是,如何在我的 tetris_canvas
小部件中获取 keyPressEvent
来响应按键?
我正在该画布内绘图,我需要响应按键,以便用户可以与该画布上的内容进行交互。
该小部件被添加到 ctor 或我的 main_window
类中的 QGridLayout
中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QWidget::keyPressEvent
是这样说的:所以你应该这样做。 (因为你没有显示你的构造函数,我猜你错过了那部分。)
之后的行也说:
您在小部件中缺少它,但在主窗口中执行它。确保在两个地方都这样做。
The
QWidget::keyPressEvent
says 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.