Advanced search

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

Dec. 15, 2017, 3:02 a.m.

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
}

enum, class enum, C++, enumerations

Articles to prepare
  • 10Number of questions
  • 66Test passed (times)
  • 60Users who passed the test
  • 70.303Average score
  • --Your average score
Start

C++C++ - Tutorial 008. Enumerations

Sept. 2, 2017, 6:25 a.m.

c++, enum, enumerations

In addition to classes, C ++ supports enumerations. In the current standard, C ++ is supported as enumeration without the scope that was introduced in earlier versions of C ++, as well as C.

enum ColorTypes {
    Green,
    Yellow,
    Red
};

So enumerations with scope

enum class ColorTypes {
    Green,
    Yellow,
    Red
};

QMLQML - Tutorial 028. Registration of custom enum in QML

July 1, 2017, 5:03 a.m.

QML, enum, qmlRegisterType

In order to use enum enum enumerations in Q ++, you need to create a class inherited from QObject and register it as a QML Type before running the QML engine in the application.

To learn, create a project using QtQuick.

The minimum version of this class with enumerations will be as follows:

#ifndef INFO_H
#define INFO_H

#include <QObject>

class Info : public QObject
{
    Q_OBJECT
public:
    enum State {
        Information,
        Debug,
        Warning,
        Error
    };
    Q_ENUM(State)
};

#endif // INFO_H
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
g
May 29, 2020, 2:32 p.m.
glushchenkoin

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

  • Result:40points,
  • Rating points-8
AS
May 26, 2020, 11:29 a.m.
Artem Sun-Dun-Chan

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

  • Result:50points,
  • Rating points-4
MN
May 25, 2020, 11:33 a.m.
Mitja Nagibin

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

  • Result:50points,
  • Rating points-4
Last comments
May 29, 2020, 1 p.m.
Evgenij Legotskoj

Django - Tutorial 023. Like Dislike system using GenericForeignKey

Думал так, но похоже что нет. {{ post.votes.likes.user.username }} Это же QuerySet будет, а не отдельный единственный объект {% for vote in post.votes %} {{ vote.user.username …
May 29, 2020, 11:43 a.m.
Vladislav Melenchuk

Django - Tutorial 023. Like Dislike system using GenericForeignKey

А как получить имя пользователя, который поставил лайк? Думал так, но похоже что нет. {{ post.votes.likes.user.username }}
May 29, 2020, 6:30 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

У меня работает. Исправлял в проекте, который приложен к статье. А что происходит в вашем коде, с учётом места вызова этого кода, я знать не могу ;) Дебажьте и добавляйте условия, кото…
MA
May 29, 2020, 6:27 a.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

QModelIndexList rowIndexes = ui->tableView->selectionModel()->selectedRows(); model->removeRows(rowIndexes.first().row(), rowIndexes.size()); model-&…
Now discuss on the forum
RS
May 30, 2020, 3:41 p.m.
Ruslan Skljuev

Минимальный размер Item

Здравствуйте, новичек в QML. Раньше у меня было несколько окон и минимальный размер считал так: minimumHeight: loGeneral.implicitHeight + 2 loGeneral.anchors.margins minimumWid…
S
RS
May 30, 2020, 11:49 a.m.
Ruslan Skljuev

QML Как при нажатии на кнопку изменить название окна?

У меня три файла: 1. QML - это Loader и Window 2. QML вход в программу - страница Loader (там есть Switch) 3. QML - MainMenu. Мне нужно в (1), чтобы если на (2) Switch.enable, то …
DK
May 29, 2020, 1:27 p.m.
Dzhon Kofi

QMap<> какой ключ лучше

это ясно. Вопрос в том, как быстро мапа будет отрабатывать, если ключом будет QModelIndex. Какой параметр индекса возьмет за ключ. И вот насколько это будет медленнее или быстрее, чем QString пр…
DK
May 29, 2020, 11:10 a.m.
Dzhon Kofi

QModelIndex становится не действительным, но валидный

Привет. Есть проблема с индексом и для меня это чистая магия: Сначала, что делаю: на вьюхе есть редактируемые ячейки. Пользователь редактирует одну, потом внезапно решает не сохраниться и ш…
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB