Q_ENUMS are “undefined” in QML?

跟風遠走 提交于 2019-12-05 08:26:36

Your problem is not the exposure of the enum, but the fact that you have a leading underscore. Once you remove that, it will work.

You need to start the enum value with uppercase letter. Some rule is necessary to distinguish enums from attached properties from enums. Leading uppercase will refer to enums, and the rest for attached properties (or undefined if not set).

Admittedly, there is also a warning in Qt itself because if you try to assign that enum value to an int or var property, you are currently not getting a warning, and having discussed that issue a little bit with the current maintainer, it seems to be a bug which will be fixed later on.

See the working code below with the correspondigly proposed solution:

main.cpp

#include <QQuickView>
#include <QQuickItem>

#include <QGuiApplication>

#include <QUrl>

class UI : public QQuickItem {
    Q_OBJECT
    Q_ENUMS(ObjectType)
public:
enum ObjectType {
        Root = 0,
        _Block
    };
};

#include "main.moc"

int main(int argc, char **argv)
{
    QGuiApplication guiApplication(argc, argv);
    qmlRegisterType<UI>("Nodes", 1, 0, "UI");
    QQuickView *view = new QQuickView;
    view->setSource(QUrl::fromLocalFile("main.qml"));
    view->show();
    return guiApplication.exec();
}

main.qml

import Nodes 1.0
import QtQuick 2.0

Rectangle {
    id: button
    width: 500; height: 500

    MouseArea {
        anchors.fill: parent
        onClicked: console.log(UI.Root)
    }
}

main.pro

TEMPLATE = app
TARGET = main
QT += quick
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

0

I had the exact same problem, and thanks to these solutions I figured out my problem. However, in case anyone else is dealing with the same mixup, here it is a little clearer.

I was using a class from C++ in QML just like here, so I had something like this in main.cpp

qmlRegisterType<EnumClass>("Enums", 1, 0, "EnumClass");

and in the .qml

import Enums 1.0

EnumClass {
    id: ec
}

and tried and tried to access ec.SomeEnum but kept getting undefined even though, the QtCreator autocomplete said ec.SomeEnum should exist.

This simply does not work, and to get this to work I had to use

EnumClass.SomeEnum

instead (just like they do here).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!