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
import QtQuick 2.10
Text {
enum MyEnum {
First = 10,
Second
}
anchors.centerIn: parent
}
Then in main.qml it can be used as follows
main.qml
import QtQuick 2.10
import QtQuick.Window 2.10
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MyText {
text: MyText.MyEnum.Second
}
}
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.
import QtQuick 2.10
Text {
enum MyEnum {
First = 10,
Second
}
anchors.centerIn: parent
text: MyText.MyEnum.Second
}
ATTENTION!!! – the following code will not work
import QtQuick 2.10
Text {
enum MyEnum {
First = 10,
Second
}
anchors.centerIn: parent
text: MyEnum.Second
}
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.
enum MyEnum {
First = -1,
Second
}
enum MySecondEnum {
First,
Second = First
}
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.