Convert String to Qt Keycode in C++

I came across the need to convert a string representing a key on the keyboard to a keycode enum like Qt::Key (or anything else). Example conversions would be:

As you see the above includes not just alpha-numeric keys but modifiers and special keys. Qt has this parsing functionality in QKeySequence’s fromString static function:

You might as why I need this conversion. Well, I have a data file generated by GhostMouse. It’s a log of what I type via the keyboard. Here’s an example of me typing ” 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}

Unfortunately, QKeySequence does not acknowledge a “Ctrl” key by itself as a key. So, I add a non-modifier key to the sequence and then subtract it from the code in that case. Here’s the complete function that should get the job done:

Leave a Reply

Your email address will not be published. Required fields are marked *