如何在PyQt5中获取QEvent的字符串名称

问题描述 投票:1回答:2

在PyQt下,我正在计时Qt事件,我想用时间写一个可读的字符串名称。使用PySide2只是调用str()会给我字符串名称,但是使用PyQt5会返回一个字符串,它是枚举值:

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

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

是否有一种使用PyQt5获取字符串名称的方法?我可以发布一个在启动时建立查找表的解决方案,该方法行得通,但想知道是否有直接的方法。

pyqt pyqt5
2个回答
0
投票
>>> type(QEvent.KeyPress)
<class 'PyQt5.QtCore.QEvent.Type'>
>>> 

PyQt5没有给出名称:

>>> PyQt5.QtCore.QEvent.KeyPress.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Type' object has no attribute 'name'
>>> 

PySide2执行:

>>> (PySide2.QtCore.QEvent.KeyPress.name)
b'KeyPress'
>>> 

0
投票

此功能适用于PyQt5PySide2。我只是通过枚举QEvent对象中的每种事件类型来创建字典。我希望有更多内置的东西。

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"
© www.soinside.com 2019 - 2024. All rights reserved.