Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

QML - Tutorial 035. Using enumerations in QML without C ++

QML, enum, enumerations

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<T>. 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.

<Name of QML object type>.<Name of enumeration>.<Name of enumerator member>

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.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Last comments
V
Feb. 14, 2019, 6:41 p.m.
Vlad15007

Спасибо огромное! Заработало!
А
Feb. 12, 2019, 9:26 a.m.
Александр90

Сам разборался, спасибо.
А
Feb. 12, 2019, 8:19 a.m.
Александр90

День добрый! Можешь выложить форму mainwindow.ui от урока? Заранее спасибо
Feb. 11, 2019, 10:51 a.m.
Евгений Легоцкой

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.
Now discuss on the forum
Feb. 15, 2019, 9:22 p.m.
IscanderChe

Доброй ночи.Скромно напоминаю о своём вопросе...
Feb. 15, 2019, 3:36 p.m.
Евгений Легоцкой

Ну я тут нашёл одно решение, но сам его не проверял. Вам нужно помещать фамилии скорее всего в ячейки заголовка, и потом просто перерисовывать их QHeaderView * header = m_ui->tableWidget...
Feb. 15, 2019, 7:53 a.m.
Евгений Легоцкой

Добрый день! Не работал с remoteobjects, поэтому глянул документацию, чтобы рассмотреть, что это за зверь. После просмотра документации сложилось стойкой впечатление, что это вполне возм...
m
Feb. 14, 2019, 6:28 p.m.
mr_roman

Нашел решение на Java. Удалось интегрировать в проект сервиса на Qt, теперь из Qt запускаю Java-код акселерометра.
Feb. 14, 2019, 11 a.m.
Евгений Легоцкой

ok. I see. You changed related name Try this {% if goal.joined.all|user_in:request.user %}
Join us in social networks

For registered users on the site there is a minimum amount of advertising