Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR: Add utility functions that convert between ints and Qt Enums (compat.py) #481

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions qtpy/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""
Compatibility functions
"""
import enum
import sys

from . import (
Expand Down Expand Up @@ -200,3 +201,26 @@ 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.
PySide2's enums are themselves classes, not enum values per se, so if
we get an integer or a class, return the class.
"""
if isinstance(enum_value, enum.Enum):
if PYSIDE2 or PYQT5:
return int(enum_value)
return enum_value.value
return enum_value


# =============================================================================
def getenumfromint(enum_class, i):
"""Get the Qt enum value from an integer"""
return enum_class(i)
22 changes: 21 additions & 1 deletion qtpy/tests/test_compat.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""Test the compat module."""

import sys

import pytest
from packaging import version

from qtpy import QtWidgets, compat
from qtpy import PYQT5, PYQT_VERSION, QtWidgets, compat
from qtpy.tests.utils import not_using_conda


Expand All @@ -22,3 +24,21 @@ 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"""
if PYQT5 and version.parse(PYQT_VERSION) <= version.parse("5.9.2"):
assert compat.getenumasint(QtWidgets.QSizePolicy.Maximum) == 4
else:
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)
if PYQT5 and version.parse(PYQT_VERSION) <= version.parse("5.9.2"):
assert enum_value == QtWidgets.QSizePolicy.Expanding
else:
assert enum_value == QtWidgets.QSizePolicy.Policy.Expanding
Loading