Reputation: 2786
I'm sure it's basic, but I've searched and came back empty-handed.
I'm using Python 3.6.4 and PyQt5
.
I want to store some custom action keys in a config file (via configparser
), and then retrieve them and respond to that keypress event.
So basically I'm looking for a function in PyQt5 that performs the reverse of chr(Qt.Key_A)
- from a character, returns a Qt.Key_.
I couldn't help myself with Googling this time, and PyQt5 is huge to peruse. I was wondering if someone could point me to the right direction.
I could use a dict, but I'm sure there must be a function that does it - I'm just not finding it.
Upvotes: 1
Views: 984
Reputation: 4629
If we are talking about alphanumeric keys only, getattr(Qt, f"Key_{key.upper()}"
should work.
from PyQt5.QtCore import Qt
def string_to_key_converter(s):
attribute = f"Key_{s.upper()}"
if hasattr(Qt, attribute):
return getattr(Qt, attribute)
else:
raise ValueError(f"Key {s} is invalid or unsupported.")
> string_to_key_converter("a") is Qt.Key_A
>>> True
Upvotes: 0
Reputation: 2786
My solution was to store the keys as ASCII code with ord()
, since they can be directly compared to Qt.Key_
objects:
from PyQt5.QtCore import Qt
ord('A') == Qt.Key_A
Out[2]: True
Upvotes: 1