1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
// networking
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
// json parsing
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>
// console output
#include <QDebug>
#include <qlogging.h>
// #include <iostream>
#include "QJsonModel.hpp"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlEngine engine;
QQmlContext *objectContext = new QQmlContext(engine.rootContext());
QStringList dataList = {
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
//objectContext->setContextProperty("sports", QVariant::fromValue(dataList));
//QQmlComponent component(&engine, "application.qml");
//QObject *object = component.create(objectContext);
// QObject *eventsList = object->findChild<QObject*>("eventsList");
// QQmlContext *componentContext = component.creationContext();
// ... delete object and objectContext when necessary
// create custom temporary event loop on stack
QEventLoop eventLoop;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QString endpoint { "https://sph-s-api.olympics.com/summer/schedules/api/ENG/schedule/discipline/ARC" };
// the HTTP request
QNetworkRequest req( (QUrl( endpoint )) );
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
//success
QString strReply = (QString)reply->readAll();
//parse json
// qDebug() << "Response:" << strReply;
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject jsonObj = jsonResponse.object();
QJsonModel * model = new QJsonModel();
// qDebug() << QJsonDocument(jsonObj["units"].toArray()).toJson();
// model->loadJson(QJsonDocument(jsonObj["units"].toArray()).toJson());
model->loadJson(strReply.toUtf8());
objectContext->setContextProperty("sports", QVariant::fromValue(model));
// componentContext->setContextProperty("sports", model);
// objectContext->setContextProperty("sports", QVariant::fromValue(dataList));
QQmlComponent component(&engine, "application.qml");
QObject *object = component.create(objectContext);
qDebug() << "Competitor:" << jsonObj["units"][0]["competitors"][0]["name"].toString();
delete reply;
}
else {
//failure
qDebug() << "Failure" <<reply->errorString();
delete reply;
}
return app.exec();
}
|