Using enumerations in QML without C ++
Well, finally they finally got it !!! There was an opportunity to declare enums immediately in QML without dancing with C ++. How to add your enumerations to QML through C ++ I described in this article . In fact, there is nothing complicated on the part of C ++, just need to write a class inherited from QObject, and register through Q_ENUM or Q_ENUMS your enumeration in this class, and register the class via qmlRegisterType.
Q_ENUM was added to Qt 5.5 to replace Q_ENUMS , and it allows QMetaEnum to be compiled at compile time using QMetaEnum::fromType . Such enumerations are now automatically registered as metatypes and can be converted to strings in QVariant or typed as a string using qDebug() .
However, according to my observations when registering transfers through Q_ENUM in QML files in Qt Creator, the code completion for these enumerations does not work, whereas when registering through Q_ENUMS everything works.
But now you can write an enumeration immediately in your custom QML type.
For example, letβs create this type of object in QML.
MyText.qml
Then in main.qml it can be used as follows
main.qml
The screen will display the number 11
As you can see, the syntax for accessing the enumeration is as follows.
. .
And it does not matter, inside the type you use this enumeration or outside it. That is, use within the type of this enumeration will look like this.
ATTENTION!!! β the following code will not work
That is, even inside a custom type, you need to refer to this type of enumeration through its name, that is, the name of the QML file.
I notice that from the point of view of organizing programs in QML, each QML file is a QML type, that is, a self-contained object that will inherit from the QObject class in the inheritance hierarchy at the C ++ level.
Also, unfortunately, the following enumeration options are not yet supported.
Among other things, the highlighting of the enum syntax in QML is not yet supported in the actual at the time of writing the Qt Creator 4.5.0 article. However, the transfers themselves work.
Last updated