3

I want get json file from local and send it to QML using this:

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

But it say that QQmlEngine::setContextForObject(): Object already has a QQmlContext but I don't understand anything from that default file.

I don't have found anything from now.

-- Added 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
        }
    }
}
9
  • I don't see any problem with the code that you've shown. It works for me when I use that same setContextProperty call. Commented Feb 15, 2021 at 15:48
  • Are you explicitly calling setContextForObject somewhere? Commented Feb 15, 2021 at 15:50
  • I will post my main.qml to see if I have put this somewhere but actually no Commented Feb 15, 2021 at 15:55
  • @Tutturuuu what is your Qt version? Commented Feb 15, 2021 at 16:00
  • @eyllanesc v6.1.0 Commented Feb 15, 2021 at 16:19

1 Answer 1

7

Maybe a bit late, but did you try importing in your Main.qml without version number?

import QtQuick
import QtQuick.Controls
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.