我想将代表键盘上的键的字符串转换为键码枚举,例如Qt::Key http://doc.qt.digia.com/4.7/qt.html#Key-enum(或其他任何东西)。转换示例如下:
-
"Ctrl"
to Qt::Key_Control
-
"Up"
to Qt::Key_Up
-
"a"
to Qt::Key_A
-
"5"
to Qt::Key_5
如您所见,上面不仅包括字母数字键,还包括修饰符和特殊键。我没有附加到 Qt 键码枚举,但 Qt 似乎有这个解析功能QKeySequence
's fromString
静态函数(参见这个直接链接 http://qt-project.org/doc/qt-4.8/qkeysequence.html#fromString):
QKeySequence fromString(const QString & str, SequenceFormat format);
您可能会理解为什么我需要这种转换。好吧,我有一个由以下代码生成的数据文件幽灵鼠标 http://www.ghost-mouse.com。这是我输入内容的日志。这是我打字的一个例子" 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}
因此,我需要一种方法将字符串“SPACE”以及表示此数据文件中的键的所有其他字符串转换为唯一的int
.
你已经走在正确的轨道上了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
key 本身就是一个 key。因此,为了支持修饰键,您必须使用“+”符号拆分字符串表示形式,然后单独处理每个子字符串。完整的功能如下:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)