enumspyqtpyqt5pyside2repr

How to get string name for QEvent in PyQt5


Under PyQt I'm timing Qt Events and I want to write a human readable string name with the time. With PySide2 just calling str() gives me the the string name but with PyQt5 it returns a string that's the enum value:

# PySide2
>>> str(QEvent.KeyPress)
'PySide2.QtCore.QEvent.Type.KeyPress'

# PyQt5
>>> str(QEvent.KeyPress)
'6'

Is there a way to get the string name using PyQt5? I can post a solution building a lookup table on startup, that works, but wondering if there is a direct way.


Solution

  • This works for PyQt5 and PySide2. I'm just create a dict by enumerating every event type in the QEvent object. I was hoping for something more built-in though.

    class EventTypes:
        """Stores a string name for each event type.
    
        With PySide2 str() on the event type gives a nice string name,
        but with PyQt5 it does not. So this method works with both systems.
        """
    
        def __init__(self):
            """Create mapping for all known event types."""
            self.string_name = {}
            for name in vars(QEvent):
                attribute = getattr(QEvent, name)
                if type(attribute) == QEvent.Type:
                    self.string_name[attribute] = name
    
        def as_string(self, event: QEvent.Type) -> str:
            """Return the string name for this event."""
            try:
                return self.string_name[event]
            except KeyError:
                return f"UnknownEvent:{event}"
    
    
    # Example Usage
    event_str = EventTypes().as_string(QEvent.UpdateRequest)
    assert event_str == "UpdateRequest"