QML中展示json数据(从c++传递的值)
来源:互联网 发布:sql server 进程死锁 编辑:程序博客网 时间:2024/06/02 07:15
1.前言
最近在搞qml,从服务器上获取一段json数据,本想直接传送至qml中展示,无奈,qt的官方文档中没有关于json如何在listview/listmodel中展示的示例代码。
从网上看到jsonmodel的第三方模块,但是觉得挺麻烦的,后来找到一种新的解法,下面写出来。
2.JSON代码从c++传至qml中
main.cpp
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();}
把QString类型字符串注册成为qml的属性,再在qml中用JavaScript解析成json变量。
jsondata.h
#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.0import QtQuick.Controls 2.1import QtQuick.Controls.Styles 1.4import QtQuick.Layouts 1.1ApplicationWindow { id:rect width: 400 height: 200 visible: true property var json_man: JSON.parse(jsondata.man)}
3.把JSON数据展示在listmodel中
main.qml
import QtQuick 2.0import QtQuick.Controls 2.1import QtQuick.Controls.Styles 1.4import QtQuick.Layouts 1.1ApplicationWindow { 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数据格式是很好用的,能直接展示出来,简直很完美!
阅读全文
2 0
- QML中展示json数据(从c++传递的值)
- Iphone利用JSON传递数据,展示在Table界面中
- Iphone利用JSON传递数据,展示在Table界面中
- Iphone利用JSON传递数据,展示在Table界面中
- handler中传递JSON数据的写法
- android 展示json数据中html格式的字段
- QML中展示文件列表的listmodel:FolderListModel
- 从C++中传送多个数据(类似于结构体)进入QML的listView中
- C#中窗体之间的数据传递
- C#中窗体之间的数据传递
- C语言中函数的数据传递
- 使用JSON格式传递数据,获取JSON的值
- Ajax中数据传递的另一种模式:JSON
- SharePoint 中使用Json传递数据到后台的 ashx
- 简析Ajax中数据传递的另一种模式:JSON
- Android数据传递中json的生成和解析
- java 中使用JSON 进行数据的传递
- 调取jSon数据--展示
- python之数据处理小技巧
- 尝试实现atoi和itoa
- 2017年总
- Android的震动与振铃
- Ajax异步开发学习笔记
- QML中展示json数据(从c++传递的值)
- 基本排序算法(冒泡、选择、插入)的效率比较
- c++模板
- php无限分类的删除
- JSON
- Python基础学习<二>
- MySQL定时执行脚本(计划任务)命令实例
- 【Apollo源码分析】系列的第三部分【prediction】
- java 快速幂取模算法