Convert string representation of keycode to Qt::Key (or any int) and back
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;
}