55
class StyleClass : public QObject {
public:
    typedef enum
        {
            STYLE_RADIAL,
            STYLE_ENVELOPE,
            STYLE_FILLED
        }  Style;

    Style m_style;
    //...
};

The .h file has the above code. How to access the above enum through QML?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

9 Answers9

63

You can wrap the enum in a class which derives from QObject (and that you expose to QML):

style.hpp :

#ifndef STYLE_HPP
#define STYLE_HPP

#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    // Qt 4
    #include <QDeclarativeEngine>
#else
    // Qt 5
    #include <QQmlEngine>
#endif

// Required derivation from QObject
class StyleClass : public QObject
{
    Q_OBJECT

    public:
        // Default constructor, required for classes you expose to QML.
        StyleClass() : QObject() {}

        enum EnStyle
        {
            STYLE_RADIAL,
            STYLE_ENVELOPE,
            STYLE_FILLED
        };
        Q_ENUMS(EnStyle)

        // Do not forget to declare your class to the QML system.
        static void declareQML() {
            qmlRegisterType<StyleClass>("MyQMLEnums", 13, 37, "Style");
        }
};

#endif    // STYLE_HPP

main.cpp:

#include <QApplication>
#include "style.hpp"

int main (int argc, char ** argv) {
    QApplication a(argc, argv);

    //...

    StyleClass::declareQML();

    //...

    return a.exec();
}

QML Code:

import MyQMLEnums 13.37
import QtQuick 2.0    // Or 1.1 depending on your Qt version

Item {
    id: myitem

    //...

    property int item_style: Style.STYLE_RADIAL

    //...
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
air-dex
  • 4,130
  • 2
  • 25
  • 25
  • 4
    Wondering if there is a way for enums not in a QObject derived class (e.g. in a software layer below the UI without Qt dependencies). – DavidJ Jun 27 '17 at 19:20
  • 1
    Note: the class registered must provide a default constructor – Fabien Aug 07 '17 at 12:48
  • You're right. I have just edited my answer with additional details. – air-dex Aug 07 '17 at 13:02
  • 1
    @DavidJ we are wondering the same thing. As far as I can tell you can't do this. Right now we are doing this: `enum MyEnum { Foo = MyOtherEnum::Foo }; Q_ENUMS(MyEnum)` – Alex Vallejo Aug 09 '17 at 15:25
  • 2
    @DavidJ As of Qt v5.8 you can do it for enums in namespaces. See [answer below](https://stackoverflow.com/a/48106787/3246449). – Maxim Paperno Jan 06 '18 at 04:37
  • This is very nice solution, however, how does one compares enum with its value? – KernelPanic Aug 26 '19 at 14:37
  • @KernelPanic Enums are integers in QML. So you can do something like `myitem.item_style === Style.STYLE_RADIAL`. – air-dex Aug 26 '19 at 16:21
  • 1
    @MaximPaperno How would you do this with a namespace enum in a header file that you are not able to modify? I tried to declare a new namespace and register the enum with a typedef like: typedef OtherEnumNamespace::OtherEnum NewEnum; Q_ENUM_NS(NewEnum) But it doesn't work – slayer Nov 01 '19 at 03:26
  • @slayer Did you mean to post this under my answer below? :) I think it's a good question, perhaps deserving a separate post. Does `Q_ENUM_NS(OtherEnumNamespace::OtherEnum)` in your new NS (with `Q_NAMESPACE` macro I presume) work? Maybe `using` instead of `typedef` for an alias? Just guessing! I think a new question might be the way to go. – Maxim Paperno Nov 01 '19 at 04:28
  • Couldn't it work with just a "using MyForeignEnum" in the class inheriting QObject ? – hl037_ Jul 13 '21 at 09:29
54

As of Qt 5.8 you can expose enums from a namespace:

Define the namespace and enum:

#include <QObject>

namespace MyNamespace
{
    Q_NAMESPACE         // required for meta object creation
    enum EnStyle {
        STYLE_RADIAL,
        STYLE_ENVELOPE,
        STYLE_FILLED
    };
    Q_ENUM_NS(EnStyle)  // register the enum in meta object data
}

Register the namespace (eg. in main(), before creating a Qml View/Context):

qmlRegisterUncreatableMetaObject(
  MyNamespace::staticMetaObject, // meta object created by Q_NAMESPACE macro
  "my.namespace",                // import statement (can be any string)
  1, 0,                          // major and minor version of the import
  "MyNamespace",                 // name in QML (does not have to match C++ name)
  "Error: only enums"            // error in case someone tries to create a MyNamespace object
);

Use it in a QML file:

import QtQuick 2.0
import my.namespace 1.0

Item {
    Component.onCompleted: console.log(MyNamespace.STYLE_RADIAL)
}

References:

https://www.kdab.com/new-qt-5-8-meta-object-support-namespaces/

http://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterUncreatableMetaObject

http://doc.qt.io/qt-5/qobject.html#Q_ENUM_NS

Maxim Paperno
  • 4,485
  • 2
  • 18
  • 22
  • 2
    In case you are wondering like me, `staticMetaObject` is an object added to your namespace by the `Q_NAMESPACE` macro. – pooya13 Jun 03 '21 at 22:43
  • Remember to re-run qmake after you add Q_NAMESPACE or the build process will not find the staticMetaObject – Matteo Sep 16 '21 at 10:20
  • The solution works,, but Is there some way the IDE (Qt Creator) can support this? As in the intelisense picking up the enums on the QML side? Because as I see, right now you need to manually write the enum names. – Curtwagner1984 Jun 08 '22 at 12:31
  • It seems to be a QtCreator bug in unresolved state https://bugreports.qt.io/browse/QTCREATORBUG-20569 – Mike Mar 15 '23 at 01:46
28

Additional information (not documented prior to Qt 5.5):

Your enum value names must start with a Capital letter.

This will work:

enum EnStyle
{
    STYLE_RADIAL,
    STYLE_ENVELOPE,
    STYLE_FILLED
};
Q_ENUMS(EnStyle)

This does not:

enum EnStyle
{
    styleRADIAL,
    styleENVELOPE,
    styleFILLED
};
Q_ENUMS(EnStyle)

You won't get any kind of error at compile time, they are just ignored by the QML engine.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Richard1403832
  • 673
  • 1
  • 9
  • 16
  • 8
    @big_gie I refer the honourable gentleman to the phrase "as of posting", and the Qt bug report I made at the time. It is now documented _because_ I took some actions to add it to the documentation. – Richard1403832 Mar 16 '16 at 12:39
  • Thanks for reporting it to Qt! Thanks to you the docs is in better shape now ;) I simply wanted to add (and refer to the exact location) that it is now documented. – big_gie Mar 17 '16 at 03:14
  • 1
    A few years ago I spent the better part of a day trying to figure out why my enums weren't showing up in QML for this reason... – ScottG May 01 '20 at 02:18
13

I found a very nice solution for using ENUMs from C++ class in QML, here: Enums in Qt QML - qml.guide. The post was so good, I felt obliged to share it here with the SO community. And IMHO attribution should always be done, hence added the link to the post.

The post basically describes:

1) How to create an ENUM type in Qt/C++:

// statusclass.h

#include <QObject>

class StatusClass
{
    Q_GADGET
public:
    explicit StatusClass();

    enum Value {
        Null,
        Ready,
        Loading,
        Error
    };
    Q_ENUM(Value)
};

2) How to register the class with QML engine as an "Uncreatable Type":
(This is the part which makes this solution nice and distinct.)

// main.cpp

...
QQmlApplicationEngine engine;
qmlRegisterUncreatableType<StatusClass>("qml.guide", 1, 0, "StatusClass",
                                        "Not creatable as it is an enum type.");
...

Use of qmlRegisterUncreatableType prevents instantiation of StatusClass in QML. A warning will be logged if a user tries to instantiate this class:

qrc:/main.qml:16 Not creatable as it is an enum type.

3) Finally, how to use the ENUM in a QML file:

// main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

import qml.guide 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component.onCompleted: {
        console.log(StatusClass.Ready); // <--- Here's how to use the ENUM.
    }
}

Important note:
ENUM is supposed to be used by referencing it with the class name, like this StatusClass.Ready. If the same class is also being used in QML as a context property...

// main.cpp

...
QQmlApplicationEngine engine;
qmlRegisterUncreatableType<StatusClass>("qml.guide", 1, 0, "StatusClass",
                                        "Not creatable as it is an enum type.");

StatusClass statusClassObj; // Named such (perhaps poorly) for the sake of clarity in the example.
engine.rootContext()->setContextProperty("statusClassObj", &statusClassObj); // <--- like this
...

...then, sometimes people accidentally use the ENUM with the context property instead of the class name.

// main.qml

...
Component.onCompleted: {
    // Correct
    console.log(StatusClass.Ready);    // 1

    // Wrong
    console.log(statusClassObj.Ready); // undefined
}
...

The reason people tend to make this mistake is because Qt Creator's autocomplete feature lists ENUM as option, both when referencing using class name as well as the context property. So just exercise caution when in such a situation.

zeFree
  • 2,129
  • 2
  • 31
  • 39
8

Qt also supports QML-defined enum types since Qt version 5.10. As an alternative to the C++-based answer by air-dex, you can now also use QML to create enum types:

Style.qml:

import QtQuick 2.0

QtObject {
  enum EnStyle {
    STYLE_RADIAL,
    STYLE_ENVELOPE,
    STYLE_FILLED
  }
}

If you only intend to use the enums in your QML code, this solution is much simpler. You can access the above enum with the Style type in qml then, for example:

import VPlayApps 1.0
import QtQuick 2.9

App {

  property int enStyle: Style.EnStyle.STYLE_RADIAL

  Component.onCompleted: {
    if(enStyle === Style.EnStyle.STYLE_ENVELOPE)
      console.log("ENVELOPE")
    else
      console.log("NOT ENVELOPE")
  }
}

See here for another usage example of a QML-based enum type.

GDevT
  • 241
  • 3
  • 4
7

All this solutions can't enabled used this enum-class as parameter for signal/slot. This code compile, but not work in QML:

class DataEmitter : public QObject
{
    Q_OBJECT

public:
    ...
signals:
    void setStyle(StyleClass::EnStyle style);
}

...

emit setStyle(StyleClass.STYLE_RADIAL);

QML-part:

Connections {
    target: dataEmitter
    onSetStyle: {
         myObject.style=style
    }
}

And this code generate runtime error, as this:

IndicatorArea.qml:124: Error: Cannot assign [undefined] to int

For this code working, you must additional registry Qt metaobject type:

qRegisterMetaType<StyleClass::EnStyle>("StyleClass.EnStyle");

More details written here: https://webhamster.ru/mytetrashare/index/mtb0/1535044840rbtgvfmjys (rus)

Xintrea
  • 388
  • 3
  • 12
  • 1
    This now also seems to be documented here: https://doc.qt.io/qt-5/qtqml-cppintegration-data.html#enumeration-types-as-signal-and-method-parameters – Marc Van Daele Mar 27 '19 at 12:09
3

Make the moc aware of your enum using the Q_ENUMS macro, as described in the docs. You must register the class that 'owns' the enum before it is used, as described in the docs.

Ashif's quote block is only valid if the enum is a global or is owned by a non-QObject derived class.

feedc0de
  • 3,646
  • 8
  • 30
  • 55
cmannett85
  • 21,725
  • 8
  • 76
  • 119
1

For Qt 6.2 and above, add the macros QML_ELEMENT and Q_ENUM() (not Q_ENUMS() which is deprecated) to the class. It should already have had Q_OBJECT too since it is a QObject, in order to register it with the Qt MOC system.

i.e.

class StyleClass : public QObject {
    Q_OBJECT       // Let the MOC know about this QObject
    QML_ELEMENT    // Make this object available to QML
public:
    typedef enum
        {
            STYLE_RADIAL,
            STYLE_ENVELOPE,
            STYLE_FILLED
        }  Style;

    Style m_style;
    Q_ENUM(Style)  // Make this enum available to QML
    //...
};

Innovations in Qt mean that these macros are sufficient and there is no longer any need to manually register the class or the enums separately.

Within QML, you would access the enum as {ClassName}.{EnumValue} with no reference to the enum name. e.g. StyleClass.STYLE_RADIAL

Paul Masri-Stone
  • 2,843
  • 3
  • 29
  • 51
0

My variant (for backward compatibility when namespaces were not available, use manual pre-defined macro ENABLE_USE_ENUM_NAMESPACES):

// enum.h
#pragma once

#include <QObject>

#ifndef ENABLE_USE_ENUM_NAMESPACES
class TaskTypeEnums : public QObject
{
    Q_OBJECT
    Q_ENUMS(TaskTypeEnum)

 public:
    explicit TaskTypeEnums(QObject *parent = nullptr): QObject(parent) {}
#else
namespace TaskTypeEnums {
    Q_NAMESPACE
#endif
    enum TaskTypeEnum {
        TaskConnectDev,
        TaskDisconnectDev,
        TaskPingDev,
        TaskResetDev,
        TaskTakeControlDev,
        TaskSetAkaModDev,
        TaskFirmwareUpdDev,
        TaskConnectDevs,
        TaskDisconnectAll,
        TaskMainTestSot,
        TaskMainTestBA,
    };
#ifndef ENABLE_USE_ENUM_NAMESPACES
};
#else
    Q_ENUM_NS(TaskTypeEnum)
}
#endif
// ----------------------------------------------------------------------------

// fragment from main.cpp
//...
#ifdef ENABLE_USE_ENUM_NAMESPACES
    qmlRegisterUncreatableMetaObject(TaskTypeEnums::staticMetaObject, "Vip.Enums.Tasks", 1, 0, "Tasks", "");
#else
    qmlRegisterType<TaskTypeEnums>("Vip.Enums.Tasks", 1, 0, "Tasks");
#endif
//...