[PyQt] How to get Qt enum class
phil at riverbankcomputing.com
Thu Aug 14 14:50:18 BST 2014
On 07/08/2014 7:27 am, Florian Bruhin wrote:
> I wrote a function to get the key name in a Qt enum from a value,
> intended for debugging mainly. This is how it looks right now:
> def qenum_key(base, value, add_base=False, klass=None):
> """Convert a Qt Enum value to its key as a string.
> base: The object the enum is in, e.g. QFrame.
> value: The value to get.
> add_base: Whether the base should be added to the printed name.
> klass: The enum class the value belongs to.
> If None, the class will be auto-guessed.
> The key associated with the value as a string if it could be
> The original value as a string if not.
> if klass is None:
> klass = value.__class__
> if klass == int:
> raise TypeError("Can't guess enum class of an int!")
> idx = klass.staticMetaObject.indexOfEnumerator(klass.__name__)
> except AttributeError:
> idx = -1
> if idx != -1:
> ret = klass.staticMetaObject.enumerator(idx).valueToKey(value)
> for name, obj in vars(base).items():
> if isinstance(obj, klass) and obj == value:
> ret = name
> ret = str(value)
> if add_base and hasattr(base, '__name__'):
> return '.'.join([base.__name__, ret])
> return ret
> Now ideally I'd just pass in the value and nothing else, however I
> didn't find a way to get the Qt class where the enum is in, e.g. get
> QFont when I have QFont.Sunken:
> <class 'PyQt5.QtGui.Weight'>
> <class 'sip.enumtype'>
> Is there a way I could do this, or do I have to pass this explicitely?
Currently QFont.Weight.__qualname__ returns 'Weight'. Maybe it should
return 'QFont.Weight' instead, the argument being that an enum is a type
and should be treated like a nested class.
Would that solve your problem?
More information about the PyQt