2

I'd like the child's handling of QKeyEvent not to be executed when it's just a modifier key that's being pressed. The following code does the job, but it's unwieldy to list them all like that. Is there a built-in way to do that?

void TextEditor::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_Shift:
    case Qt::Key_Control:
    case Qt::Key_Alt:
    case Qt::Key_Meta:
    case Qt::Key_Mode_switch:
        return QPlainTextEdit::keyPressEvent(event);
    }

    // handle the event...
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74

2 Answers2

1

You can use this QKeyEvent::modifiers() member for this purpose. If the result is

const bool isModifier = ( event->modifiers() != Qt::NoModifier );

true then the pressed key was a modifier.

So for you code it means the following modifications.

void TextEditor::keyPressEvent( QKeyEvent* event )
{
    if ( event->modifiers() != Qt::NoModifier )
    {
        return QPlainTextEdit::keyPressEvent(event);
    }

    // Handle the event ...
}

Or if you want to handle some special key combination why not just use this way:

void TextEditor::keyPressEvent( QKeyEvent* aKeyEvent )
{
    if ( aKeyEvent->matches( QKeySequence::Copy ) )
    {
        // Your copy stuff ...
        return;
    }
    // else if ( aKeyEvent->matches( ... ) ) // Other key combinations ...

    return QPlainTextEdit::keyPressEvent( aKeyEvent);
}
p.i.g.
  • 2,815
  • 2
  • 24
  • 41
  • Yes, I know about `QKeyEvent::modifiers()`, but will this also work when I hold one and press another? Also, I want to handle the key combinations like Ctrl+C normally. – LogicStuff May 16 '15 at 05:28
  • In this case I think that you need another approach. Don't you want to handle the special key combinations separately ? If yes, then you can use the [QKeyEvent::matches(...)](http://doc.qt.io/qt-5/qkeyevent.html#matches) function. I update my answer with this. – p.i.g. May 17 '15 at 11:39
0

a better way to do this in 3 lines:

if(event->modifiers()){
   event->ignore(); // or don't ignore and handle the event 
                    // switching the modifiers
}

this is the modifiers defined by qt:

Qt::NoModifier  
Qt::ShiftModifier   
Qt::ControlModifier
Qt::AltModifier 
Qt::MetaModifier    
Qt::KeypadModifier  
Qt::GroupSwitchModifier

you can do a switch for filtering.