From dc26c97920419d55e556a5fd5e178d12b630c29c Mon Sep 17 00:00:00 2001 From: Zach Pearson Date: Thu, 18 Apr 2024 13:58:37 -0700 Subject: [PATCH] compat.py: Add utility functions that convert between ints and Qt Enums --- qtpy/compat.py | 19 +++++++++++++++++++ qtpy/tests/test_compat.py | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/qtpy/compat.py b/qtpy/compat.py index 4c6d428f..8fc7ac71 100644 --- a/qtpy/compat.py +++ b/qtpy/compat.py @@ -200,3 +200,22 @@ def isalive(obj): return shiboken.isValid(obj) return None + + +# ============================================================================= +def getenumasint(enum_value): + """Get the integer value of a Qt enum + For example: + Qt.AlignmentFlag.AlignBaseline -> 256 + Qt.WidgetAttribute.WA_AcceptDrops -> 78 + If an integer is passed in, simply return it. + """ + if isinstance(enum_value, int): + return enum_value + return enum_value.value + + +# ============================================================================= +def getenumfromint(enum_class, i): + """Get the Qt enum value from an integer""" + return enum_class(i) diff --git a/qtpy/tests/test_compat.py b/qtpy/tests/test_compat.py index 1e1fc28f..da53606f 100644 --- a/qtpy/tests/test_compat.py +++ b/qtpy/tests/test_compat.py @@ -1,4 +1,5 @@ """Test the compat module.""" + import sys import pytest @@ -22,3 +23,15 @@ def test_isalive(qtbot): with qtbot.waitSignal(test_widget.destroyed): test_widget.deleteLater() assert compat.isalive(test_widget) is False + + +def test_getenumasint(): + """Test compat.getenumasint""" + assert compat.getenumasint(QtWidgets.QSizePolicy.Policy.Maximum) == 4 + assert compat.getenumasint(5) == 5 + + +def test_getenumfromint(): + """Test compat.getenumfromint""" + enum_value = compat.getenumfromint(QtWidgets.QSizePolicy.Policy, 7) + assert enum_value == QtWidgets.QSizePolicy.Policy.Expanding