はじめてのQtアプリです。画面にHello Worldを表示してから、ECMAScriptを評価した結果をログに保存します。
Hello Worldの部分は、雛形のプロジェクトに含まれていたままで、ECMAScriptの評価の部分だけマニュアルを眺めながら書きました。C++のコードからECMAScriptを実行し、その結果をJSON形式で受け取る例です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QGuiApplication> | |
#include <QQmlApplicationEngine> | |
#include <QtScript> | |
int main(int argc, char *argv[]) { | |
QGuiApplication app(argc, argv); | |
QQmlApplicationEngine appEngine; | |
appEngine.load(QUrl(QStringLiteral("qrc:/main.qml"))); | |
QScriptEngine scriptEngine; | |
QString script = "var x = { a: true, b: 'c', c: 7, d: [ 1, 2, 3 ] }; JSON.stringify(x, null, 2);"; | |
QJsonDocument json = QJsonDocument::fromJson(scriptEngine.evaluate(script).toString().toUtf8()); | |
QJsonObject x = json.object(); | |
qDebug() << "a: " << x["a"].toBool() << ", b: " << x["b"].toString() << ", c: " << x["c"].toInt(); | |
auto arr = x["d"].toArray(); | |
qDebug("d:"); | |
for (int i = 0; i < arr.size(); i++) { | |
qDebug() << " " << arr[i].toInt(); | |
} | |
return app.exec(); | |
} |
これまでは、Node.jsを起動してJSON形式のファイルに保存したものをC++で読み込んで構文解析していたので、かなり簡素化できます。