本文介绍了qt qml 对象已经有一个 QQmlContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从本地获取 json 文件并将其发送到 QML:
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();
}
但它说 QQmlEngine::setContextForObject(): Object 已经有一个 QQmlContext
但我不了解该默认文件中的任何内容.
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.
-- 添加了 Main.qml --
-- 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
}
}
}
推荐答案
可能有点晚了,但是您是否尝试在没有版本号的情况下导入 Main.qml?
Maybe a bit late, but did you try importing in your Main.qml without version number?
import QtQuick
import QtQuick.Controls
这篇关于qt qml 对象已经有一个 QQmlContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!