Issue
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.
Solution
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.
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.
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)
Output:
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
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.