You were already on the right track by looking at QKeySequence , as it 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 recognize the Ctrl key itself as a key. Thus, in order to support modifier keys, you can add the key to the modifier in the sequence, and then subtract it from the code. The following is the full function:
uint toKey(QString const & str) { QKeySequence seq(str); uint keyCode; // We should only working with a single key here if(seq.count() == 1) keyCode = seq[0]; else { // Should be here only if a modifier key (eg Ctrl, Alt) is pressed. assert(seq.count() == 0); // Add a non-modifier key "A" to the picture because QKeySequence // seems to need that to acknowledge the modifier. We know that A has // a keyCode of 65 (or 0x41 in hex) seq = QKeySequence(str + "+A"); assert(seq.count() == 1); assert(seq[0] > 65); keyCode = seq[0] - 65; } return keyCode; }
source share