我正在尝试过滤按键/释放事件,以便为我的应用程序设置长按事件的计时器(例如,当按下错误3秒钟时弹出菜单)。我遇到了一些与QKeyEvent自动重复不一致的问题。这是我的代码:
Mainview::Mainview (QWidget *parent) :
QMainWindow (parent)
{
setupUi (this);
qApp->installEventFilter(this); // event filter for key presses
...
}
void Mainview::ControlsPressEvent(QKeyEvent *event)
{
if ((event->isAutoRepeat()))
{
return;
}
QString s = QString("Key PRESS event: %1.").arg(event->text());
qDebug() << s;
}
void Mainview::ControlsReleaseEvent(QKeyEvent *event)
{
if ((event->isAutoRepeat()))
{
return;
}
QString s = QString("Key RELEASE event: %1.").arg(event->text());
qDebug() << s;
}
bool Mainview::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
qDebug() << event << " | " << obj;
/* Only grab the key event from the parent window object */
if (obj->objectName() == "MainviewClassWindow")
{
this->ControlsPressEvent(dynamic_cast<QKeyEvent*>(event));
return true;
}
}
else if (event->type() == QEvent::KeyRelease)
{
qDebug() << event << " | " << obj;
/* Only grab the key event from the parent window object */
if (obj->objectName() == "MainviewClassWindow")
{
this->ControlsReleaseEvent(dynamic_cast<QKeyEvent*>(event));
return true;
}
}
else
{
return QObject::eventFilter(obj, event);
}
return false;
}
有时它有效,有时则不然:
这是一个工作示例中的qDebug输出,我按一次键,按住并释放:
"Key PRESS event: ."
QKeyEvent(KeyRelease, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
QKeyEvent(KeyPress, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
QKeyEvent(KeyRelease, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
QKeyEvent(KeyPress, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
QKeyEvent(KeyRelease, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
QKeyEvent(KeyPress, Key_Down, autorepeat, count=1) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key RELEASE event: ."
这是一个非工作示例中的qDebug输出,我按下该键一次,按住并释放:
QKeyEvent(KeyPress, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key PRESS event: ."
QKeyEvent(KeyRelease, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key RELEASE event: ."
QKeyEvent(KeyPress, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key PRESS event: ."
QKeyEvent(KeyRelease, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key RELEASE event: ."
QKeyEvent(KeyPress, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key PRESS event: ."
QKeyEvent(KeyRelease, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key RELEASE event: ."
QKeyEvent(KeyPress, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key PRESS event: ."
QKeyEvent(KeyRelease, Key_Down) | QWidgetWindow(0xa522a0, name = "MainviewClassWindow")
"Key RELEASE event: ."
为什么QKeyEvent的autorepeat
成员在设置时不一致?也许这是按键,按住和释放处理的错误方法?
由于