I'm using PyQt5. When I write a keyPressEvent handler, I would like to be able to print, for debugging purposes, a human-readable description of what keys were pressed. I want to be able to print such a thing no matter what, regardless of how many keys were pressed in the event, or whether they were modifiers or "regular" keys.
I have seen this previous question in which the accepted answer (using C++) suggests creating a QKeySequence and using its .toString
method. I can do this like this:
def keyPressEvent(self, event):
print("got a key event of ", QKeySequence(event.key()).toString())
However, this does not always work. For instance, if I press the Shift key, it will result in an encoding error when I try to output (or if I try to encode it to UTF-8). This seems to be because QKeySequence does not work on isolated modifier keys:
>>> QKeySequence(Qt.Key_Shift).toString().encode('unicode-escape')
b'\\u17c0\\udc20'
It gives gibberish instead of what I would expect, namely "Shift". It works if I use Qt.SHIFT
(sort of, in that it gives "Shift+"), but that is of no use, because Qt.SHIFT
is not what I get in event.key()
if I press the Shift key.
How can I get Qt to give me a printable representation of anything that might ever be the value of event.key()
, where event
is a QKeyEvent?