Evgenii Legotckoi
July 1, 2017, 4:03 p.m.

QML - Tutorial 028. Registration of custom enum in QML

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

Next, you need to register this class as a QML Type in the main function. This requires a QtQml header file and a qmlRegisterType function.

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml> // Include QtQml to use qmlRegisterType

#include "info.h" // Connect the header file of the Info class

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<Info>("info", 1, 0, "Info"); // Register this class as a module

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

After that it will only be necessary to connect the new QML module in the main.qml file and use the enumerations to display the text. We will output the message "Message 0", "Message 1", etc. The numbers will be taken from the enumerations.

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

import info 1.0  // Import Module

Window {
    visible: true
    width: 360
    height: 360
    title: qsTr("Enumeration")

    ListView {
        anchors.fill: parent
        delegate: Item {
            height: 48
            width: parent.width
            Text {
                anchors.fill: parent
                text: "Message " + model.text

                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
            }
        }

        model: ListModel {
            // Use the enumerations from C ++
            ListElement {text: Info.Information}
            ListElement {text: Info.Debug}
            ListElement {text: Info.Warning}
            ListElement {text: Info.Error}
        }
    }
}

Appearance of the application will be as follows:

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 24, 2025, 12:04 p.m.
    UPD: Переписал логику воспроизведения через стороннюю библиотеку BASS. Там выбрать можно
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…