utils.debug: Improve qenum_key.

This commit is contained in:
Florian Bruhin 2014-08-07 07:35:05 +02:00
parent 19b80c1e90
commit 2546c871c8
2 changed files with 34 additions and 6 deletions

View File

@ -46,6 +46,21 @@ class QEnumKeyTests(unittest.TestCase):
key = debug.qenum_key(QFrame, QFrame.Sunken) key = debug.qenum_key(QFrame, QFrame.Sunken)
self.assertEqual(key, 'Sunken') self.assertEqual(key, 'Sunken')
def test_add_base(self):
"""Test with add_base=True."""
key = debug.qenum_key(QFrame, QFrame.Sunken, add_base=True)
self.assertEqual(key, 'QFrame.Sunken')
def test_int_noklass(self):
"""Test passing an int without explicit klass given."""
with self.assertRaises(TypeError):
debug.qenum_key(QFrame, 42)
def test_int(self):
"""Test passing an int with explicit klass given."""
key = debug.qenum_key(QFrame, 0x0030, klass=QFrame.Shadow)
self.assertEqual(key, 'Sunken')
class TestDebug(unittest.TestCase): class TestDebug(unittest.TestCase):

View File

@ -130,28 +130,41 @@ def trace_lines(do_trace):
sys.settrace(None) sys.settrace(None)
def qenum_key(base, value): def qenum_key(base, value, add_base=False, klass=None):
"""Convert a Qt Enum value to its key as a string. """Convert a Qt Enum value to its key as a string.
Args: Args:
base: The object the enum is in, e.g. QFrame. base: The object the enum is in, e.g. QFrame.
value: The value to get. value: The value to get.
add_base: Whether the base should be added to the printed name.
klass: The enum class the value belongs to.
If None, the class will be auto-guessed.
Return: Return:
The key associated with the value as a string, or None. The key associated with the value as a string if it could be found.
The original value as a string if not.
""" """
if klass is None:
klass = value.__class__ klass = value.__class__
if klass == int:
raise TypeError("Can't guess enum class of an int!")
try: try:
idx = klass.staticMetaObject.indexOfEnumerator(klass.__name__) idx = klass.staticMetaObject.indexOfEnumerator(klass.__name__)
except AttributeError: except AttributeError:
idx = -1 idx = -1
if idx != -1: if idx != -1:
return klass.staticMetaObject.enumerator(idx).valueToKey(value) ret = klass.staticMetaObject.enumerator(idx).valueToKey(value)
else: else:
for name, obj in vars(base).items(): for name, obj in vars(base).items():
if isinstance(obj, klass) and obj == value: if isinstance(obj, klass) and obj == value:
return name ret = name
return None break
else:
ret = str(value)
if add_base and hasattr(base, '__name__'):
return '.'.join([base.__name__, ret])
else:
return ret
def signal_name(sig): def signal_name(sig):