C++ 捕获修饰键 Qt
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17204142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capturing modifier keys Qt
提问by user29291
I am trying to understand how to handle various events with Qt and have found an issue I cannot understand with key modifiers e.g. CtrlShiftAltetc. I have made a default Qt GUI Application in Qt Creator extending QMainWindow and have found that the following example does not produce understandable results.
我试图了解如何使用 Qt 处理各种事件,并发现了一个我无法理解的问题,例如按键修饰符CtrlShiftAlt等。我在 Qt Creator 中创建了一个默认的 Qt GUI 应用程序扩展 QMainWindow 并发现以下示例无法理解结果。
void MainWindow::keyPressEvent(QKeyEvent *event)
{
qDebug() << "Modifier " << event->modifiers().testFlag(Qt::ControlModifier);
qDebug() << "Key " << event->key();
qDebug() << "Brute force " << (event->key() == Qt::Key_Control);
}
Using the modifiers() function on the event never is true while the brute force method returns the correct value.
对事件使用 modifiers() 函数永远不会为真,而蛮力方法返回正确的值。
What have I done wrong?
我做错了什么?
回答by Freedom_Ben
Try using this to check for shift:
尝试使用它来检查班次:
if(event->modifiers() & Qt::ShiftModifier){...}
if(event->modifiers() & Qt::ShiftModifier){...}
this to check for control:
这是为了检查控制:
if(event->modifiers() & Qt::ControlModifier){...}
if(event->modifiers() & Qt::ControlModifier){...}
and so on. That works well for me.
等等。这对我很有效。
EDIT:
编辑:
To get the modifiers of a wheel event, you need to check the QWheelEvent
object passed to your wheelEvent()
method:
要获取滚轮事件的修饰符,您需要检查QWheelEvent
传递给您的wheelEvent()
方法的对象:
void MainWindow::wheelEvent( QWheelEvent *wheelEvent )
{
if( wheelEvent->modifiers() & Qt::ShiftModifier )
{
// do something awesome
}
else if( wheelEvent->modifiers() & Qt::ControlModifier )
{
// do something even awesomer!
}
}
回答by Pavel Strakhov
According to the documentation, QKeyEvent::modifiers
cannot always be trusted. Try to use QApplication::keyboardModifiers()
static function instead.
根据文档,QKeyEvent::modifiers
不能总是被信任。尝试改用QApplication::keyboardModifiers()
静态函数。
From Qt 5 Doc. – Qt::KeyboardModifiers QKeyEvent::modifiers() const:
来自Qt 5 文档。– Qt::KeyboardModifiers QKeyEvent::modifiers() const:
Warning:This function cannot always be trusted. The user can confuse it by pressing both Shiftkeys simultaneously and releasing one of them, for example.
警告:此功能不能总是被信任。例如,用户可以通过同时按下两个Shift键并释放其中一个来混淆它。