How to declare enums in Python and expose to QML?
-
In C++ one can simply declare an enum as following:
enum class MyEnum{One, Two, Three}
Then using the
Q_ENUM
macro and registering the object usingqRegisterType
one is able to use the enums in QML. How can I do this in PySide2. I am aware that Python possesses enum capabilities (from enum import Enum
) but how can I expose these to QML? I have tried to import theQ_ENUM
macro fromPySide2.QtCore
but that didn't work. -
An enumeration is a set of symbolic names bound to unique, constant values . Within an enumeration, the values can be compared by identity, and the enumeration itself can be iterated over. In Python 3.4 (PEP 435) , you can make Enum the base class.
from enum import Enum class Directions(Enum): East, West,North,South = range(4) print(Directions.North.value)
-
An enumeration is a set of symbolic names bound to unique, constant values . Within an enumeration, the values can be compared by identity, and the enumeration itself can be iterated over. In Python 3.4 (PEP 435) , you can make Enum the base class.
from enum import Enum class Directions(Enum): East, West,North,South = range(4) print(Directions.North.value)
@galewinston
Yes, but that does not address the OP's problem of exposing to QML; the vagaries of Python are not at issue.@daljit97
Bad news, I'm afraid, I think: https://stackoverflow.com/questions/57693019/how-to-declare-enums-in-pyside-2-and-expose-them-to-qml, August 2019:At the moment, there is no equivalent, because PySide2 does not implement Q_ENUMS: see bug PYSIDE-957. In addition to this, the implementation of Property also has problems: see bug PYSIDE-900. A fully working QML enum example for PyQt5 is given here - but of course you cannot test it with PySide2.
So it works from PyQt5 but not from PySide2, and remains unresolved in the latter.