[solved] Registering an ENUM in QML

  • Dear all,

    In the Qt documentation it is explained that enumerated types defined in a QObject derived class could be used in QML. However there is no sample of how to do the registration call per se. Could you provide a sample ?

    Also, it is possible to register uncreatable types. They are referring to enum types or a QObject derived class? Which are the requirements of theses classes? Could you provide a sample?

    Joaquim Duran

  • Hi, to register an enum you can simply use the "Q_ENUMS":http://qt-project.org/doc/qt-5/qobject.html#Q_ENUMS macro, e.g.
    class Test : public QObject
    Q_PROPERTY(TestEnum testEnum READ getTestEnum WRITE setTestEnum NOTIFY testEnumChanged)

    explicit Test(QObject *parent = 0);

    enum class TestEnum {
        One, Two, Three
    // getter, setter and signal omitted

    TestEnum m_testEnum;
    if you register this Test class to the QML engine you can just access the enum property and use it like Test.One etc.
    There might be one drawback, as far as I know enums are still converted to integer values, so you can't print the string value in QML, just the int :(
    I mean if you have a QML object of Test and you do this:
    you will only see 0, 1 or 2 and not One, Two or Three sadly

    for you second question you can simply use "qmlRegisterUncreatableType":http://qt-project.org/doc/qt-5/qqmlengine.html#qmlRegisterUncreatableType or maybe better "qmlRegisterSingletonType":http://qt-project.org/doc/qt-5/qqmlengine.html#qmlRegisterSingletonType if you need a single object.

  • Xander84, your sample about enumerations it has been very useful.

    To access to the enumerated value is done in the same way as accessing to a property.

    Test {
    testEnum: Test.One

    Joaquim Duran

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.