QML参考错误-在c ++ / QML集成期间未定义<thing>

时间:2019-03-27 10:44:43

标签: c++ qt qml qt5 integration

我正在尝试构建混合的c ++ / QML应用程序,但是在尝试使两个部分进行通信和交互时遇到了一个问题。 目的是通过使用qmlApplicationEngine的setContextProperties方法在QML中使用嵌入式C ++对象。

我一直在看这篇文章QT 5.7 QML - Reference Error: Class is not defined,因为问题非常相似,但不幸的是,该解决方案不适用于此处。我对Qt还是很陌生,所以也许解决方案很明显,但我无法弄清楚。

所以我有3个文件,main.cppthing.hmain.qml

main.cpp:

#include "thing.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

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

    Thing thing;
    engine.rootContext()->setContextProperty("thing", &thing);
    thing.setColor(Qt::green);

    return app.exec();
}

调用thing.h:

class Thing : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)

public:
    Thing() : _color(Qt::black), _text("text") { }

    Q_INVOKABLE void clicked() { setColor(Qt::blue); }

    QColor color() const {return _color;}
    void setColor(const QColor &color) {
        _color = color;
        emit colorChanged();
    }
signals:
    void colorChanged();

private:
    QColor _color;
};

和main.qml:

Window {id: main
    width: 100; height: 100
    color: thing.color

    MouseArea {
        anchors.fill: parent
        onClicked: thing.clicked();
    }
}

运行此代码时,我得到“ qrc:/main.qml:6:ReferenceError:未定义的事物”,它指向main.qml中的执行color: thing.color。我该如何运作?

1 个答案:

答案 0 :(得分:2)

您可以在加载主组件之前尝试公开根上下文属性“ thing”。一旦创建组件实例并首次评估其绑定,它将确保您的“ thing”属性可用。

#include "thing.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    Thing thing;

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("thing", &thing);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    thing.setColor(Qt::green);

    return app.exec();
}