Capturing modifier keys Qt

风流意气都作罢 提交于 2019-12-10 04:29:42

问题


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. Ctrl Shift Alt etc. 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.

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.

What have I done wrong?


回答1:


Try using this to check for shift:

if(event->modifiers() & Qt::ShiftModifier){...}

this to check for control:

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:

void MainWindow::wheelEvent( QWheelEvent *wheelEvent )
{
    if( wheelEvent->modifiers() & Qt::ShiftModifier )
    {
        // do something awesome
    }
    else if( wheelEvent->modifiers() & Qt::ControlModifier )
    {
        // do something even awesomer!
    }
}



回答2:


According to the documentation, QKeyEvent::modifiers cannot always be trusted. Try to use QApplication::keyboardModifiers() static function instead.


From Qt 5 Doc. – Qt::KeyboardModifiers QKeyEvent::modifiers() const:

Warning: This function cannot always be trusted. The user can confuse it by pressing both Shift keys simultaneously and releasing one of them, for example.



来源:https://stackoverflow.com/questions/17204142/capturing-modifier-keys-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!