[Solved]Calling function from QML to C++ class to get Json string PROBLEM.
-
Hi, I have problem, when i try to load Json string from my "Main.qml", but then I load Json file from another qml it's work fine, in "Main.qml" i get an error: "ReferenceError: json is not defined"
My main.cpp:
@....
QApplication app(argc, argv);
File file_obj;QQuickView *view = new QQuickView; view->setSource(QStringLiteral("qml/Main.qml")); view->rootContext()->setContextProperty("json", (QObject *)&file_obj); view->show();@
File loader class - file_loader.h:
@class File : public QObject
{
Q_OBJECT
Q_PROPERTY(QString string READ get_file_string NOTIFY file_Status)public:
QString kb_layout;
void parse_kb_layout();QString get_file_string() { return kb_layout; } Q_INVOKABLE QString fileLoad(QString filen) { QString fileName = filen; QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) exit(1); QStringList stringList; QTextStream textStream(&file); this->kb_layout = textStream.readAll(); file.close(); return kb_layout; emit file_Status(0); }
signals:
void file_Status(int i) ;
};@Main.qml:
@Rectangle {
id: main;
width: 1280;
height: 1024;
color: "#112836"Component.onCompleted: { json.fileLoad("colors.json") var jsonData = JSON.parse(json.string); }
}@
And my another qml file where i get Json string - test.qml(Main.qml and test.qml are in the same directory):
@Rectangle {
id: boxes
width: 1280
height: 864;
color: "transparent";
y:160;............
Component.onCompleted: { json.fileLoad("boxes.json"); var jsonData = JSON.parse(json.string); }
}@
Json files is valid.
Any idea what is wrong?
Thanks in advice ;) -
Fail was here...
@QQuickView *view = new QQuickView;
view->rootContext()->setContextProperty("translation", (QObject *)&translation_obj);
view->rootContext()->setContextProperty("json", (QObject *)&file_obj); // Moved up this line... :D
view->setSource(QStringLiteral("qml/Main.qml"));
view->show();@Now everything works fine ;)