[PyQt] How to get Qt enum class

Florian Bruhin me at the-compiler.org
Thu Aug 7 07:27:22 BST 2014


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?

Florian

-- 
http://www.the-compiler.org | me at the-compiler.org (Mail/XMPP)
             GPG 0xFD55A072 | http://the-compiler.org/pubkey.asc
         I love long mails! | http://email.is-not-s.ms/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 819 bytes
Desc: not available
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20140807/426e875c/attachment-0001.sig>


More information about the PyQt mailing list