Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing modifier keys Qt

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?

like image 356
user29291 Avatar asked Jun 20 '13 01:06

user29291


People also ask

How do you use a modifier key?

The modifier key is held down while another key is pressed one or more times. For example, a modifier key is used to move the cursor across text a word or sentence at a time, and it is used to enter commands such as print, open and close. For Windows PCs, see Control key, Alt key and Windows key.

Where is the modifier key?

On an IBM compatible computer, modifier keys include Alt, Ctrl, Shift, and the Windows key. On the Apple Macintosh computer, the Control, Option, Command, and Shift keys are modifier keys. Additionally, most laptop and some desktop keyboards contain an Fn modifier key.

Is function key a modifier key?

The Fn key, short form for function, is a modifier key on many keyboards, especially on laptops, used in a compact layout to combine keys which are usually kept separate. It is typically found on laptops due to their keyboard size restrictions.


1 Answers

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!
    }
}
like image 188
Freedom_Ben Avatar answered Sep 19 '22 06:09

Freedom_Ben