qt qml 对象已经有一个 QQmlContext

qt qml Object already has a QQmlContext

我想从本地获取 json 文件并使用以下方法将其发送到 QML:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    engine.rootContext()->setContextProperty("text_json", "{\"text1\": \"Loading\"}");
    QObject::connect(
                &engine,
                &QQmlApplicationEngine::objectCreated,
                &app,
                [url](QObject *obj, const QUrl &objUrl) {
                    if (!obj && url == objUrl)
                        QCoreApplication::exit(-1);
                },
                Qt::QueuedConnection
    );
    engine.load(url);

    return app.exec();
}

但是它说 QQmlEngine::setContextForObject(): Object already has a QQmlContext 但我不明白那个默认文件的任何内容。

我现在还没有找到任何东西。

-- 添加了 Main.qml --

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    id: window
    width: 640
    height: 480
    visible: true
    title: qsTr("Stack")

    property var text_json: ({"text1": "Loading"})

    header: ToolBar {
        contentHeight: toolButton.implicitHeight

        ToolButton {
            id: toolButton
            icon.source: "./images/ruby.png"

            font.pixelSize: Qt.application.font.pixelSize * 1.6
            onClicked: {
                drawer.open()
            }
        }

        Label {
            text: stackView.currentItem.title
            anchors.centerIn: parent
        }
    }
}

可能有点晚了,但是您是否尝试过在没有版本号的情况下导入 Main.qml?

import QtQuick
import QtQuick.Controls