How to define new enums in QML?
-
Sorry if the answer lies somewhere in the documentation already, I usually try to find everything online but in this case I could not.
How can I define new enums directly in QML? I know that you can mark any enum defined in a C++ class with the Q_ENUMS macro, but in my case I want to define an enum that describes various states of a QtQuick component I'm crafting.
Alternatively, if I define a Q_ENUMS in one C++ class that I later import in some part of my QtQuick project, how can I make those enums visible outside of the class?
For example:
I define class MyClass { Q_ENUMS enum MyStates { off, on }; };
Then I register this type in the namespace "MyNamespace" and write this in main.qml:
@import MyNamespace 1.0
Item {
MyNamespace { id: ns }
}@
At this point, can I use those enums in another QML file? For example, in MyComponent.qml
@Item {
property var state: MyClass.off
}@
Will that work? I mean, take for example Text.NativeRendering. I guess that's an enum, and is globally accessible in the QML type system once registered, is that correct? -
@#ifndef ENUMS_HPP
#define ENUMS_HPP#include <QObject>
class Enums : public QObject
{
Q_OBJECTQ_ENUMS(AngleUnits)
public:
enum AngleUnits
{
degrees,
radians,
centesimal
};// This is a wrapper, uncreatable type
Enums() = delete;
Enums(const Enums&) = delete;
Enums& operator=(const Enums&) = delete;
};#endif // ENUMS_HPP
@@int main(int argc, char* argv[])
{
// stuff
qmlRegisterUncreatableType<Enums>("Shared", 1, 0, "Enums", "Enums is not a type, just a wrapper for enums used in the program");
// stuff
return app.exec();
}
@@import Shared 1.0
Item {
Component.onCompleted: console.log(Enums.centesimal);
}
@Why does this print undefined?? What am I doing wrong?
-
Here is an example with working Q_ENUMS:
@#ifndef PERSON_H
#define PERSON_H#include <QQuickItem>
#include <QDebug>class Person : public QQuickItem
{
Q_OBJECT
Q_INTERFACES(QQmlParserStatus)
Q_ENUMS(TestEnum)
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
QString m_name;public:
explicit Person(QQuickItem *parent = 0);enum TestEnum { Test1, Test2, Test3 }; QString name() const { return m_name; } virtual void componentComplete() { // Perform some initialization here now that the object is fully created qDebug() << m_name; }
signals:
void nameChanged(QString arg);
public slots:
void setName(QString arg)
{
if (m_name != arg) {
m_name = arg;
emit nameChanged(arg);
}
}
};#endif // PERSON_H@
Maybe the enum names must be Uppercase because they are constants?