PyQt允许枚举值和字符串

时间:2016-09-24 12:12:51

标签: python pyqt pyqt4 pyqt5 pyside

在PySide中,我可以使用values属性获取包含可能/允许的枚举器值及其字符串表示的字典。例如: QtWidgets.QMessageBox.StandardButton.values.items()。如何在PyQt4 / PyQt5中实现相同的功能?这甚至可能吗?我在文档中没有发现任何相关内容。

1 个答案:

答案 0 :(得分:1)

PySide有一个内置的枚举类型(Shiboken.EnumType),支持对名称/值进行迭代。它还支持name属性,您可以使用该属性直接从其值中获取枚举器名称。

不幸的是,PyQt从未拥有过这些功能,所以你必须推出自己的解决方案。使用QMetaType进行此操作很诱人,但有些课程没有必要staticMetaObject。特别是,Qt命名空间没有一个,它使用QMetaType排除了很大一组枚举。

因此,更通用的解决方案是使用python的dir函数来构建双向映射,如下所示:

def enum_mapping(cls, enum):
    mapping = {}
    for key in dir(cls):
        value = getattr(cls, key)
        if isinstance(value, enum):
            mapping[key] = value
            mapping[value] = key
    return mapping

enum = enum_mapping(QMessageBox, QMessageBox.StandardButton)

print('Ok = %s' % enum['Ok'])
print('QMessageBox.Ok = %s' % enum[QMessageBox.Ok])
print('1024 = %s' % enum[1024])
print()

for item in sorted(enum.items(), key=str):
    print('%s = %s' % item)

输出:

Ok = 1024
QMessageBox.Ok = Ok
1024 = Ok

Abort = 262144
Apply = 33554432
ButtonMask = -769
Cancel = 4194304
Close = 2097152
Default = 256
Discard = 8388608
Escape = 512
FirstButton = 1024
FlagMask = 768
Help = 16777216
Ignore = 1048576
LastButton = 134217728
No = 65536
NoAll = 131072
NoButton = 0
NoToAll = 131072
Ok = 1024
Open = 8192
Reset = 67108864
RestoreDefaults = 134217728
Retry = 524288
Save = 2048
SaveAll = 4096
Yes = 16384
YesAll = 32768
YesToAll = 32768
-769 = ButtonMask
0 = NoButton
1024 = Ok
1048576 = Ignore
131072 = NoToAll
134217728 = RestoreDefaults
16384 = Yes
16777216 = Help
2048 = Save
2097152 = Close
256 = Default
262144 = Abort
32768 = YesToAll
33554432 = Apply
4096 = SaveAll
4194304 = Cancel
512 = Escape
524288 = Retry
65536 = No
67108864 = Reset
768 = FlagMask
8192 = Open
8388608 = Discard