Evgenii Legotckoi
Evgenii LegotckoiDec. 15, 2017, 4:02 a.m.

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

Content

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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

m
  • June 20, 2022, 8:26 a.m.

А как правильно зарегистрировать C++ enum, допустим

enum CppEnumType {
 Foo,
 Bar
};

чтобы использовать его в QML как

property CppEnumType: CppEnumType.Foo

У меня никак не получается тип проперти сделать enum из C++, только как int

Evgenii Legotckoi
  • June 21, 2022, 3:09 a.m.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
m
moogoNov. 22, 2024, 3:17 p.m.
Mosquito Spray System Effective Mosquito Systems for Backyard | Eco-Friendly Misting Control Device & Repellent Spray - Moogo ; Upgrade your backyard with our mosquito-repellent device! Our misters conce…
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 10:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 10:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks