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

Ala*_*ing 6 c++ qt keycode type-conversion string-parsing

我想将表示键盘上的键的字符串转换为像Qt :: Key(或其他任何东西)的键码枚举.转换示例如下:

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

如您所见,上面不仅包括字母数字键,还包括修饰符和特殊键.我没有连接到Qt的键码枚举,但似乎Qt拥有在这个分析功能QKeySequencefromString静态函数(见本直接链接):

QKeySequence fromString(const QString & str, SequenceFormat format);
Run Code Online (Sandbox Code Playgroud)

您可能就像我需要这种转换一样.好吧,我有一个由GhostMouse生成的数据文件.这是我输入内容的日志.这是我输入的一个例子" 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}
Run Code Online (Sandbox Code Playgroud)

所以我需要一种方法将字符串"SPACE"和表示此数据文件中的键的所有其他字符串转换为唯一的int.

jdi*_*jdi 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"
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)