Solved QML and C++11 Enums
-
Hi guys... I have a litter question..
Can I use C++11 enums in QML ??
I can define my enums on my c++ class and export it to qml, but can I use instead normal enum a c++11 enum using:
enum class A{v1,v2}
????
that is my quesiton
regards
-
Hi @freddy311082 Yes indeed we can definitely use. You have to declare it as a metatype using
Q_DECLARE_METATYPE
. I regularly use them. Check it here and usage is here. -
-
@freddy311082 You're Welcome. Please mark the post as solved if done.
-
@p3c0 but how can you use following enums?
enum class Animal { dog, deer, cat, bird, human }; // enum class enum class Mammal { kangaroo, deer, human }; // another enum class
Note that
deer
is in both enum classes. How you distinguish these? -
-
Hi. I had the same issue and as Qt Enums doesn't let you use as you describe before, what I did was create a single class per Enum, also I export each class to QML to use it. So, if you have
enum Animal { dogAnimal, deerAnimal, catAnimal, birdAnimal, humanAnimal };
at least I did:
class Animal : public QObject { Q_OBJECT public: Animal(QObject* parent = nullptr); enum class AnimalEnum { dog, deer, cat, bird, human };; virtual ~Animal(){} }; Q_DECLARE_METATYPE(Animal::AnimalEnum);
The same for Mammal enum. After that, you can register this classes to be used in QML, and you will be available to do
Animal.deer Mammal.deer
at least, is what I do when I have a situation like yours
Regards