Qt Key Pressevent Enter

Anudorannador picture Anudorannador · Sep 3, 2014 · Viewed 15.3k times · Source
void LoginModle::keyPressEvent(QKeyEvent *event)
{
    qDebug() << event->key() << "\t" << Qt::Key_Enter << "\t" << QKeyEvent::Enter;
    if( event->key() == Qt::Key_Enter)
        OKButtonClicked();
    else
        QDialog::keyPressEvent(event);
}

This code is very simple, class LoginModle inherits from QWidget. run this code and when I press Enter, it shows:

16777220     16777221    10

It means that my Enter in keyboard is 16777220, but in Qt, it was defined as 16777221.

My system is Elementary OS (Freya), which is based on Ubuntu 14.04.

Is there something wrong with my driver or just the program's mistake ?

Answer

Tanuj Mathur picture Tanuj Mathur · Sep 3, 2014

The Enter key referred to by Qt::Key_Enter is the Enter key on the numeric keypad. You are pressing the "Enter" key that's next to the letters on your keyboard. That's known as the Return key, and its value is represented by Qt::Key_Return, which equals 16777220.

So, in order to support both key presses, you would modify the if statement as follows:

if( (event->key() == Qt::Key_Enter) || (event->key() == Qt::Key_Return))
        OKButtonClicked();
    else
        QDialog::keyPressEvent(event);