Evgenii Legotckoi
Dec. 15, 2017, 3:02 p.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

  1. import QtQuick 2.10
  2.  
  3. Text {
  4. enum MyEnum {
  5. First = 10,
  6. Second
  7. }
  8.  
  9. anchors.centerIn: parent
  10. }

Then in main.qml it can be used as follows

main.qml

  1. import QtQuick 2.10
  2. import QtQuick.Window 2.10
  3.  
  4. Window {
  5. visible: true
  6. width: 640
  7. height: 480
  8. title: qsTr("Hello World")
  9.  
  10. MyText {
  11. text: MyText.MyEnum.Second
  12. }
  13. }

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.

  1. import QtQuick 2.10
  2.  
  3. Text {
  4. enum MyEnum {
  5. First = 10,
  6. Second
  7. }
  8.  
  9. anchors.centerIn: parent
  10. text: MyText.MyEnum.Second
  11. }

ATTENTION!!! - the following code will not work

  1. import QtQuick 2.10
  2.  
  3. Text {
  4. enum MyEnum {
  5. First = 10,
  6. Second
  7. }
  8.  
  9. anchors.centerIn: parent
  10. text: MyEnum.Second
  11. }

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.

  1. enum MyEnum {
  2. First = -1,
  3. Second
  4. }
  5.  
  6. enum MySecondEnum {
  7. First,
  8. Second = First
  9. }

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.

Recommended articles on this topic

By article asked0question(s)

2

Do you like it? Share on social networks!

m
  • June 20, 2022, 6:26 p.m.

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

  1. enum CppEnumType {
  2. Foo,
  3. Bar
  4. };

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

  1. property CppEnumType: CppEnumType.Foo

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

Evgenii Legotckoi
  • June 21, 2022, 1:09 p.m.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup