我用消息过滤器响应按键消息
bool CMainWindow::eventFilter(QObject *target, QEvent *event)
{
if(QEvent::KeyPress == event->type())
{
std::cout<<"press"<<std::endl;
return true;
}
else if(QEvent::KeyRelease == event->type())
{
std::cout<<"release"<<std::endl;
return;
}
return false;
}
我按着一个键不动结果显示
press
release
press
release
press
release
press
release
press
release
我根本就没有松开,为什么会不停的press,release。MFC里面不会,应该不是我键盘问题吧。
Qt QKeyEvent 消息过滤 多个按键
------解决方案--------------------
刚看了下源码。
qkeymaper_win.cpp里面
// If we have a record, it means that the key is already pressed, the state is the same
// so, we have an auto-repeating key
if (rec) {
if (code < Qt::Key_Shift
------解决方案--------------------
code > Qt::Key_ScrollLock) {
k0 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, code,
Qt::KeyboardModifier(state), rec->text, true, 0,
scancode, msg.wParam, nModifiers);
k1 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, code,
Qt::KeyboardModifier(state), rec->text, true, 0,
scancode, msg.wParam, nModifiers);
}
}
注释告诉我们,Qt的行为是这样的,你也看到了他发送了2个事件 k0 keyrelease. k1 keypress.
所以能收到2个。
解决方法:通过QKeyEvent::isAutoRepeat() 来判断。
bool Widget::eventFilter(QObject *obj, QEvent *event)
{
if(QEvent::KeyPress == event->type())
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug()<<"press event" <<keyEvent->isAutoRepeat();
return true;
}
else if(QEvent::KeyRelease == event->type())
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug() <<"release event" << keyEvent->isAutoRepeat();
return true;
}
return false;
}