Search code examples
qtoptimizationevent-handlingsignalskeyevent

Where to determine what key was pressed


For example I have two type of keys that I need to handle in different ways. So, I should determine what type of pressed key is. I can separate keys in signal level, that is determine what key was pressed and emit appropriate signal:

void QueryTextEdit::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
        case Qt::Key_Slash :
        {
            emit slashWasPressed();
            break;
        }
        default :
        {
            emit otherKeyWasPressed(event);
            break;
        }
    }
}

Or I can catch all signal in a single slot and handle key types here:

keyHandler(QKeyEvent *event) {
    if (event->key() == Qt::Key_Slash) {
        // do something
        return;
    } else { 
        // do something
    }
}

What way is more preferable?


Solution

  • Take a look at http://qt-project.org/doc/qt-4.8/qkeyevent.html#key This provides the int code of the key that was pressed :)

    Or you can take a look at QKeyEvent::text() which returns the unicode for the key event

    Edit: @your comment

    If you want to handle the slash key and discard all others, I would go with approach #2.