QML中展示json数据(从c++传递的值)

1 篇文章 0 订阅

1.前言

最近在搞qml,从服务器上获取一段json数据,本想直接传送至qml中展示,无奈,qt的官方文档中没有关于json如何在listview/listmodel中展示的示例代码。

从网上看到jsonmodel的第三方模块,但是觉得挺麻烦的,后来找到一种新的解法,下面写出来。

2.JSON代码从c++传至qml中

main.cpp
把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数据格式是很好用的,能直接展示出来,简直很完美!

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值