【问题标题】:qt qml Object already has a QQmlContextqt qml 对象已经有一个 QQmlContext
【发布时间】:2021-12-25 17:15:13
【问题描述】:

我想从本地获取 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
        }
    }
}

【问题讨论】:

  • 我认为您显示的代码没有任何问题。当我使用相同的 setContextProperty 调用时,它对我有用。
  • 您是否在某处明确调用setContextForObject
  • 我会发布我的 main.qml 看看我是否把它放在某个地方但实际上没有
  • @Tutturuuu 你的 Qt 版本是多少?
  • @eyllanesc v6.1.0

标签: c++ qt qml qt6


【解决方案1】:

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

import QtQuick
import QtQuick.Controls

【讨论】:

  • 我不再参与此项目,但我测试了您的解决方案,它不再显示错误,而是在应用程序内找不到 text_json
猜你喜欢
  • 2019-04-13
  • 2021-03-22
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多