Get the "name" of a key from QKeyEvent in Qt

Ben picture Ben · Feb 13, 2014 · Viewed 20.3k times · Source

Is there an easy way of getting the name of a key (so something like "uparrow" from a key event instead of just getting the key code "16777235")? Do I have to make a list of key names myself?

Answer

Alex P picture Alex P · Feb 13, 2014

Using human-readable names in your code

You can use the Qt::Key enum, or get the key as a string with QKeyEvent::text().

From QKeyEvent documentation:

int QKeyEvent::key () const

Returns the code of the key that was pressed or released.

See Qt::Key for the list of keyboard codes. These codes are independent of the underlying window system. Note that this function does not distinguish between capital and non-capital letters, use the text() function (returning the Unicode text the key generated) for this purpose.

...

Qt::Key is an enum that maps numeric key IDs (like the return value of QKeyEvent::key()) to programmer-readable names like Qt::Key_Up.

If you only care about alphanumeric keys, you can also use QKeyEvent::text() to get the value:

QString QKeyEvent::text () const

Returns the Unicode text that this key generated. The text returned can be an empty string in cases where modifier keys, such as Shift, Control, Alt, and Meta, are being pressed or released. In such cases key() will contain a valid value.

See also Qt::WA_KeyCompression.

Displaying human-readable names to the user

Use QKeySequence::toString() or build your own table of "nice" names.

The easiest way to get human-readable key names to show to the user is to use QKeySequence::toString().

Here's an example:

Qt::Key key = Qt::Key_Up;
qDebug() << QKeySequence(key).toString(); // prints "Up"

If you don't like the names that QKeySequence uses (e.g. you want to use "Up Arrow" instead of "Up"), you'll need to make your data table to remap the enum values to your preferred names.