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

标签 c++ qt qml qt5 integration

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

我一直在看这篇文章QT 5.7 QML - Reference Error: Class is not defined由于问题非常相似,但不幸的是该解决方案不适用于此处。我还是 Qt 的新手,所以也许解决方案很明显,但我想不出来。

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

主要.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: thing is not defined”,它指的是在 main.qml 中执行 color: thing.color。我怎样才能让它工作?

最佳答案

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

#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();
}

关于c++ - QML 引用错误 - <thing> 在 c++/QML 集成期间未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55375300/

相关文章:

c++ - 如何在 C++ 中的两点之间插入 "k"点数​​?

c++ - Qt c++ 应用程序抓取

zooming - 在Qt Quick(QML)中实现缩放/缩放的正确方法

c++ - 如何将 libc++ 与调试符号链接(symbolic link)?

c++ - 我如何让 Xcode Instruments 将未分配的内存报告为泄漏?

c++ - 删除指针时出现段错误

c++ - 带有 qt5 (qml) 的无框窗口

qt - QTableWidgetItem如何设置单元格边框和背景色?

c++ - 如何通过 Qt 5.6 将 QML 应用程序窗口设置为透明?

qt - 当 QML 项目的大小发生变化时,如何保持其右上角的位置?