PyQt 允许枚举值和字符串 [英] PyQt allowed enumeration values and strings

查看:99
本文介绍了PyQt 允许枚举值和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In PySide I can get the dictionary with possible/allowed enumerator values and their string representations by using values attribute. For example: QtWidgets.QMessageBox.StandardButton.values.items(). How to achieve the same in PyQt4/PyQt5? Is that even possible? I have found nothing about this in the docs.

推荐答案

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

PySide has a built-in enum type (Shiboken.EnumType) which supports iteration over the names/values. It also supports a name attribute, which you can use to get the enumerator name directly from its value.

不幸的是,PyQt 从来没有这些功能,所以你必须推出自己的解决方案.为此使用 QMetaType 很诱人,但有些类没有必要的 staticMetaObject.特别是,Qt 命名空间没有,这就排除了使用 QMetaType 来处理非常大的枚举组.

Unfortunately, PyQt has never had these features, so you will have to roll your own solution. It's tempting to use QMetaType for this, but some classes don't have the necessary staticMetaObject. In particular, the Qt namespace doesn't have one, which rules out using QMetaType for a very large group of enums.

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

So a more general solution would be to use python's dir function to build a two-way mapping, like this:

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

这篇关于PyQt 允许枚举值和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆