1// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
2//
3// SPDX-License-Identifier: GPL-3.0-or-later
4
5#include "jsondisplaymodel.h"
6
7#include <QDebug>
8#include <QTableView>
9
10namespace {
11static std::string feild{"feild"};
12static std::string lines{"lines"};
13}
14
15class JsonDisplayModelPrivate
16{
17 friend class JsonDisplayModel;
18 Json::Value cacheValue;
19 QStringList cacheFeild;
20 QVector<QStringList> cacheLines;
21};
22
23JsonDisplayModel::JsonDisplayModel(QObject *parent)
24 : QStandardItemModel (parent)
25 , d (new JsonDisplayModelPrivate)
26{
27
28}
29
30JsonDisplayModel::~JsonDisplayModel()
31{
32 if (d)
33 delete d;
34}
35
36void JsonDisplayModel::parseJson(const Json::Value &value)
37{
38 d->cacheValue = value;
39 Json::Value feild = d->cacheValue[::feild];
40 Json::Value lines = d->cacheValue[::lines];
41 if (d->cacheFeild.isEmpty()) {
42 if (!feild.empty()) {
43 for (uint idx = 0; idx < feild.size(); idx ++) {
44 d->cacheFeild << QString::fromStdString(feild[idx].asString());
45 }
46 setColumnCount(d->cacheFeild.size());
47 }
48 }
49
50 if (!lines.empty()) {
51 setRowCount(0);
52 d->cacheLines.clear();
53 for (auto line : lines) {
54 QStringList lineData;
55 for (auto feildCacheOne : d->cacheFeild) {
56 int findIdx = -1;
57 for (uint idx = 0; idx < feild.size(); idx ++) {
58 if (feildCacheOne.toStdString() == feild[idx].asString()) {
59 findIdx = idx;
60 break;
61 }
62 }
63 if (findIdx >= 0) {
64 lineData << QString::fromStdString(line[findIdx].asString());
65 }
66 }
67 d->cacheLines << lineData;
68 }
69 setRowCount(d->cacheLines.size());
70 }
71}
72
73QVariant JsonDisplayModel::headerData(int section, Qt::Orientation orientation,
74 int role) const
75{
76 if (d->cacheFeild.isEmpty() || d->cacheValue[::feild].empty())
77 return {};
78
79 if (role == Qt::DisplayRole && orientation == Qt::Horizontal
80 && section >= 0 && section < d->cacheFeild.size()) {
81 QString feildOne = d->cacheFeild[section];
82 return feildOne;
83 }
84 return {};
85}
86
87bool JsonDisplayModel::setHeaderData(int section, Qt::Orientation orientation,
88 const QVariant &value, int role)
89{
90 if (d->cacheFeild.empty()) {
91 return QStandardItemModel::setHeaderData(section, orientation, value, role);
92 } else {
93 return true;
94 }
95}
96
97QModelIndex JsonDisplayModel::index(int row, int column, const QModelIndex &parent) const
98{
99 return QStandardItemModel::index(row, column, parent);
100}
101
102QVariant JsonDisplayModel::data(const QModelIndex &index, int role) const
103{
104 if (!index.isValid())
105 return {};
106
107 int row = index.row();
108 int col = index.column();
109
110 if (row >= 0 && col >= 0) {
111 if (role == Qt::DisplayRole) {
112 return d->cacheLines[row][col];
113 }
114 }
115 return QStandardItemModel::data(index, role);
116}
117