Last active
March 10, 2021 13:52
-
-
Save ales-erjavec/f86555f0c63069eb2334a5798af3d500 to your computer and use it in GitHub Desktop.
qvariant_cast "like" in PyQt5/PySide2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import overload, Union, Type, TypeVar, Any | |
from functools import lru_cache | |
from PyQt5.QtCore import QObject, pyqtProperty as Property | |
@lru_cache(maxsize=200) | |
def _converter(type_: Union[type, str]): | |
class Obj(QObject): | |
__slots__ = ("field",) | |
def _set(self, val): | |
self.field = val | |
def _get(self): | |
return self.field | |
prop = Property(type_, _get, _set) | |
def convert(value): | |
inst = Obj() | |
inst.field = value | |
inst.setProperty('prop', value) | |
return inst.property('prop') | |
return convert | |
T = TypeVar("T") | |
@overload | |
def qvariant_cast(type_: Type[T], value) -> T: ... | |
@overload | |
def qvariant_cast(type_: str, value) -> Any: ... | |
def qvariant_cast(type_: Union[type, str], value): | |
""" | |
Like :cpp:`T qvariant_cast(const QVariant &value)` | |
The full range of QVariant casts is not exposed by PyQt5/PySide therefore | |
this method trys to subvert existing apis to achieve functional parity. | |
Example | |
------- | |
>>> qvariant_cast(str, None) | |
'' | |
>>> qvariant_cast(int, None) | |
0 | |
>>> qvariant_cast(bool, '1') | |
True | |
>>> qvariant_cast(bool, '0') | |
False | |
>>> qvariant_cast('QStringList', None) | |
[] | |
>>> qvariant_cast(QBrush, Qt.red).color().name() | |
'#ff0000' | |
""" | |
converter = _converter(type_) | |
return converter(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment