[PyQt] How to get Qt enum class

Phil Thompson phil at riverbankcomputing.com
Thu Aug 14 14:50:18 BST 2014


On 07/08/2014 7:27 am, Florian Bruhin wrote:
> Hi,
> 
> 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.
> 
>     Args:
>         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.
> 
>     Return:
>         The key associated with the value as a string if it could be 
> found.
>         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!")
>     try:
>         idx = klass.staticMetaObject.indexOfEnumerator(klass.__name__)
>     except AttributeError:
>         idx = -1
>     if idx != -1:
>         ret = klass.staticMetaObject.enumerator(idx).valueToKey(value)
>     else:
>         for name, obj in vars(base).items():
>             if isinstance(obj, klass) and obj == value:
>                 ret = name
>                 break
>         else:
>             ret = str(value)
>     if add_base and hasattr(base, '__name__'):
>         return '.'.join([base.__name__, ret])
>     else:
>         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:
> 
>>>> QFont.Bold.__class__
> <class 'PyQt5.QtGui.Weight'>
>>>> QFont.Bold.__class__.__class__
> <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?

Phil


More information about the PyQt mailing list