QWidget keyPressEvent 覆盖
我已经尝试了半个世纪来覆盖 QT 中的 QWidgets keyPressEvent 函数,但它不起作用。我不得不说我是 CPP 新手,但我知道 ObjC 和标准 C。
我的问题如下所示:
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
};
QSGameBoard 是我的 QWidget 子类,我需要重写 keyPressEvent 并在每个事件上触发 SIGNAL 以通知某些已注册的对象。
我在 QSGameBoard.cpp 中重写的 keyPressEvent 如下所示:
void QSGameBoard::keyPressEvent(QKeyEvent *event) {
printf("\nkey event in board: %i", event->key());
//emit keyCaught(event);
}
当我将 QSGameBoard:: 更改为 QWidget:: 时,它接收事件,但我无法发出信号,因为编译器抱怨范围。如果我这样写,该函数根本不会被调用。
这里有什么问题?
I'm trying for half an eternity now overriding QWidgets keyPressEvent function in QT but it just won't work. I've to say i am new to CPP, but I know ObjC and standard C.
My problem looks like this:
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
};
QSGameBoard is my QWidget subclass and i need to override the keyPressEvent and fire a SIGNAL on each event to notify some registered objects.
My overridden keyPressEvent in QSGameBoard.cpp looks like this:
void QSGameBoard::keyPressEvent(QKeyEvent *event) {
printf("\nkey event in board: %i", event->key());
//emit keyCaught(event);
}
When i change QSGameBoard:: to QWidget:: it receives the events, but i cant emit the signal because the compiler complains about the scope. And if i write it like this the function doesn't get called at all.
What's the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:
正如其他用户所指出的,我最初概述的方法并不是解决此问题的正确方法。
瓦斯科·里纳尔多的回答
我之前给出的(尽管不完美)解决方案如下:
看起来您的小部件没有获得“焦点”。覆盖鼠标按下事件:
这是一个工作示例的源代码:
QSGameBoard.h
QSGameBoard.cpp
main.cpp
EDIT:
As pointed out by other users, the method I outlined originally is not the proper way to resolve this.
Answer by Vasco Rinaldo
The previous (albeit imperfect) solution I gave is given below:
Looks like your widget is not getting "focus". Override your mouse press event:
Here's the source code for a working example:
QSGameBoard.h
QSGameBoard.cpp
main.cpp
您不必自己重新实现mousePressEvent来调用setFocus。 Qt已经计划好了。
将
FocusPolicy
设置为Qt::ClickFocus
以通过鼠标单击获取键盘焦点。正如手册中所说:
You don't have to reimplement mousePressEvent yourself just to call setFocus. Qt planed it already.
Set the
FocusPolicy
toQt::ClickFocus
to get the keybordfocus by mouse klick.As said in the manual:
将 FocusPolicy 设置为 Qt::ClickFocus 以通过鼠标单击获取键盘焦点。
setFocusPolicy(Qt::ClickFocus);
Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by mouse klick.
setFocusPolicy(Qt::ClickFocus);