将keycode的字符串表示形式转换为Qt :: Key(或任何int)并返回

时间:2012-12-25 21:44:33

标签: c++ qt type-conversion string-parsing keycode

我想将表示键盘上的键的字符串转换为类似Qt::Key的键码枚举(或其他任何内容)。转换示例如下:

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

如您所见,上面不仅包括字母数字键,还包括修饰符和特殊键。我没有附加到Qt键码枚举,但似乎Qt在QKeySequence的{​​{1}}静态函数中有这种解析功能(参见this direct link):

fromString

您可能就像我需要这种转换一样。好吧,我有GhostMouse生成的数据文件。这是我输入内容的日志。这是我输入QKeySequence fromString(const QString & str, SequenceFormat format);

的示例
" It "

所以我需要一种方法将字符串“SPACE”和表示此数据文件中的键的所有其他字符串转换为唯一的{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}

3 个答案:

答案 0 :(得分:8)

您已经在正确的轨道上查看QKeySequence,因为这可用于在字符串和密钥代码之间进行转换:

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"

由OP

添加

以上不支持Ctrl,Alt,Shift等修饰键。不幸的是,QKeySequence不会将Ctrl键确认为键。因此,要支持修饰键,可以在序列中添加非修饰键,然后从代码中减去它。以下是完整的功能:

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 (e.g. 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;
}

答案 1 :(得分:1)

您可以恢复大多数关键代码,例如QKeySequence::fromString("SPACE")[0]返回32.它不适用于Shift,Ctrl等,因此您应该自己处理一些字符串。

答案 2 :(得分:1)

在一行中,尝试一下:

qDebug() << QKeySequence(event->modifiers()+event->key()).toString() << '\n';

首先,我调用QKeySequence构造函数,然后使用toString()将其转换为字符串。

输出(最后一个是Windows键):

"Alt+??"

"Alt+A"

"Alt+A"

"Alt+A"

"A"

"S"

"F1"

"F2"

"Home"

"Ins"

"Num+8"

"Num+5"

"Num+4"

"Num+."

"Num++"

"Num+-"

"Num+/"

"Num+*"

"??"