Convert string representation of keycode to Qt::Key (or any int) and back

Alan Turing picture Alan Turing · Dec 25, 2012 · Viewed 8.7k times · Source

I would like to convert a string representing a key on the keyboard to a keycode enum like Qt::Key (or anything else). Example conversions would be:

  • "Ctrl" to Qt::Key_Control
  • "Up" to Qt::Key_Up
  • "a" to Qt::Key_A
  • "5" to Qt::Key_5

As you see the above includes not just alpha numeric keys but modifiers and special keys. I'm not attached to the Qt keycode enum, but it seems that Qt has this parsing functionality in QKeySequence's fromString static function (see this direct link):

QKeySequence fromString(const QString & str, SequenceFormat format);

You might as why I need this conversion. Well, I have a data file generated by GhostMouse. It's a log of what I type. Here's an example of me typing " It ":

{SPACE down}
{Delay 0.08}
{SPACE up}
{Delay 2.25}
{SHIFT down}
{Delay 0.11}
{i down}
{Delay 0.02}
{SHIFT up}
{Delay 0.03}
{i up}
{Delay 0.05}
{t down}
{Delay 0.08}
{t up}
{Delay 0.05}
{SPACE down}
{Delay 0.12}
{SPACE up}

So I need a way to convert the string "SPACE" and all the other strings representing keys in this data file to a unique int.

Answer

jdi picture jdi · Dec 25, 2012

You were already on the right track looking at QKeySequence, as this can be used to convert between string and key codes:

QKeySequence seq = QKeySequence("SPACE");
qDebug() << seq.count(); // 1

// If the sequence contained more than one key, you
// could loop over them. But there is only one here.
uint keyCode = seq[0]; 
bool isSpace = keyCode==Qt::Key_Space;
qDebug() << keyCode << isSpace;  // 32 true

QString keyStr = seq.toString().toUpper();
qDebug() << keyStr;  // "SPACE"

added by OP

The above does not support modifier keys such as Ctrl, Alt, Shift, etc. Unfortunately, QKeySequence does not acknowledge a Ctrl key by itself as a key. So, to support modifier keys, you must split the string representation using "+" sign and then process separately each substring. The following is the complete function:

QVector<int> EmoKey::splitKeys(const QString &comb)
{
    QVector<int> keys;
    const auto keyList = comb.split('+');
    for (const auto &key: keyList) {
        if (0 == key.compare("Alt", Qt::CaseInsensitive)) {
            keys << Qt::Key_Alt;
        } else if (0 == key.compare("Ctrl", Qt::CaseInsensitive)) {
            keys << Qt::Key_Control;
        } else if (0 == key.compare("Shift", Qt::CaseInsensitive)) {
            keys << Qt::Key_Shift;
        } else if (0 == key.compare("Meta", Qt::CaseInsensitive)) {
            keys << Qt::Key_Meta;
        } else {
            const QKeySequence keySeq(key);
            if (1 == keySeq.count()) {
                keys << keySeq[0];
            }
        }
    }
    return keys;
}