1.前言
最近在搞qml,从服务器上获取一段json数据,本想直接传送至qml中展示,无奈,qt的官方文档中没有关于json如何在listview/listmodel中展示的示例代码。
从网上看到jsonmodel的第三方模块,但是觉得挺麻烦的,后来找到一种新的解法,下面写出来。
2.JSON代码从c++传至qml中
main.cpp
jsondata.h
把QString类型字符串注册成为qml的属性,再在qml中用JavaScript解析成json变量。
jsondata.h
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <jsondata.h>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
JsonData jsondata;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("jsondata",&jsondata);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
#ifndef JSONDATA_H
#define JSONDATA_H
#include <QObject>
class JsonData : public QObject
{
Q_OBJECT
Q_PROPERTY(QString man READ man NOTIFY manChanged)
public:
JsonData();
QString man() {return QString("[{\"name\":\"Joy\",\"age\":30},{\"name\":\"James\",\"age\":36},{\"name\":\"Lily\",\"age\":20}]");}
signals:
void manChanged();
private:
QString man2;
};
#endif // JSONDATA_H
jsondata.cpp
#include "jsondata.h"
JsonData::JsonData()
{
}
main.qml
import QtQuick 2.0 import QtQuick.Controls 2.1 import QtQuick.Controls.Styles 1.4 import QtQuick.Layouts 1.1 ApplicationWindow { id:rect width: 400 height: 200 visible: true property var json_man: JSON.parse(jsondata.man) }
3.把JSON数据展示在listmodel中
main.qml
import QtQuick 2.0
import QtQuick.Controls 2.1
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.1
ApplicationWindow {
id:rect
width: 400
height: 200
visible: true
property var json_man: JSON.parse(jsondata.man)
ListView {
id:man_table
x: 20
y: 20
width: 359
height: 158
keyNavigationWraps: false
snapMode: ListView.SnapToItem
highlightRangeMode: ListView.ApplyRange
anchors.margins: 5
spacing: 3
model: json_man
delegate: table_model
}
Component{
id:table_model
RowLayout{
spacing: 10
Layout.fillWidth:true
Label{
text: json_man[index].name
}
Label{
text: json_man[index].age
}
}
}
}
4.总结
json数据格式是很好用的,能直接展示出来,简直很完美!