-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPyQtJsonModel.py
303 lines (240 loc) · 8.48 KB
/
PyQtJsonModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# 2017-2020 by Gregor Engberding , MIT License
import logging
import sys
from PySide2.QtCore import QAbstractItemModel, QModelIndex, Qt, QJsonDocument, QJsonParseError
from PySide2.QtWidgets import QApplication, QTreeView
DEMO_JSON = b"""{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}"""
DEMO_DICT = {
"firstName" : "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
class QJsonTreeItem:
"""A tree node with parent and children
For easy display by the QJsonModel
"""
def __init__(self, parent=None, value=None):
self.parent = parent
self.children = []
self.value = None
self.key = None
self.typename = None
if value:
self.init_tree(value, parent)
def row(self):
"""Special for Qt, the row(aka. index) in it´s parent children
:return: Own index in parent´s children or -1
"""
if self.parent is not None:
return self.parent.children.index(self)
return -1
def init_tree(self, value, parent=None):
"""Initializes the tree below parent with value
:param value: the value to be inserted below parent
:param parent: insert value below this parent, if None, it´s the root node
:return: the tree-structure of QJsonTreeItems
"""
root_item = QJsonTreeItem(parent=parent)
root_item.key = "root"
if isinstance(value, dict):
for key, val in value.items():
child = self.init_tree(val, root_item)
child.key = key
root_item.children.append(child)
elif isinstance(value, list):
for idx, val in enumerate(value):
child = self.init_tree(val, root_item)
child.key = idx
root_item.children.append(child)
else:
root_item.value = value
root_item.typename = type(value).__name__
return root_item
@property
def as_dict(self):
typename = self.typename
if (children := self.children) and typename == "dict":
return {child.key: child.as_dict for child in children}
elif (children := self.children) and typename == "list":
return [child.as_dict for child in children]
return self.value
class QJsonModel(QAbstractItemModel):
"""To be used as a model with a QTreeView to show contents of a JSON
"""
def __init__(self, parent=None, json_data=None):
super().__init__(parent)
self.document = None
self.root_item = QJsonTreeItem()
self.headers = ["key", "value", "type"]
if json_data:
self.update_data(json_data)
def update_data(self, json_data):
"""New data for the model
:param json_data: binary JSON, a dict or a filename
:return:
"""
error = QJsonParseError()
if isinstance(json_data, dict):
self.document = QJsonDocument.fromVariant(json_data)
else:
try:
self.document = QJsonDocument.fromJson(json_data, error)
except TypeError:
# here the message is generated by Qt
# FIXME Subscripted generics cannot be used with class and instance checks
pass
if self.document is not None:
self.beginResetModel()
if self.document.isArray():
self.root_item.init_tree(list(self.document.array()))
else:
self.root_item = self.root_item.init_tree(self.document.object())
self.endResetModel()
return
else:
# try as file
if self.load_from_file(filename=json_data):
return
msg = f"Unable to load as JSON:{json_data}"
logging.log(logging.ERROR, msg)
raise ValueError(msg)
def load_from_file(self, filename):
"""Loads JSON from filename
:param filename: name of json-file
:return: (bool) True=success, False=failed
"""
if filename is None or filename is False:
return False
with open(filename, "rb") as file:
if file is None:
return False
json_data = file.read()
self.update_data(json_data)
return True
def data(self, index: QModelIndex, role: int = ...):
if not index.isValid():
return None
item = index.internalPointer()
col = index.column()
if role == Qt.DisplayRole:
if col == 0:
return item.key
elif col == 1:
return item.value
elif col == 2:
return item.typename
elif role == Qt.EditRole:
if col == 0:
return item.key
elif col == 1:
return item.value
return None
def setData(self, index: QModelIndex, value, role: int = ...) -> bool:
if role == Qt.EditRole:
col = index.column()
item = index.internalPointer()
if col == 0:
item.key = value
return True
elif col == 1:
item.value = value
item.typename = type(value).__name__
return True
return False
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return self.headers[section]
return None
def index(self, row: int, column: int, parent: QModelIndex = ...):
if not self.hasIndex(row, column, parent):
return QModelIndex()
if not parent.isValid():
parent_item = self.root_item
else:
parent_item = parent.internalPointer()
try:
child_item = parent_item.children[row]
return self.createIndex(row, column, child_item)
except IndexError:
return QModelIndex()
def parent(self, index: QModelIndex):
if not index.isValid():
return QModelIndex()
child_item = index.internalPointer()
parent_item = child_item.parent
if parent_item == self.root_item:
return QModelIndex()
return self.createIndex(parent_item.row(), 0, parent_item)
def rowCount(self, parent: QModelIndex = ...):
if parent.column() > 0:
return 0
if not parent.isValid():
parent_item = self.root_item
else:
parent_item = parent.internalPointer()
return len(parent_item.children)
def columnCount(self, parent: QModelIndex = ...):
return 3
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
if not index.isValid():
return Qt.NoItemFlags
if index.column() != 2:
return Qt.ItemIsEditable | super().flags(index)
return super().flags(index)
@property
def as_dict(self):
return self.root_item.as_dict
if __name__ == '__main__':
app = QApplication(sys.argv)
# model = QJsonModel(json_data=DEMO_JSON)
# or use a dict as data-source
# model = QJsonModel(json_data=DEMO_DICT)
# or use a filename
model = QJsonModel(json_data="json-data.json")
view = QTreeView()
view.setModel(model)
view.show()
print(f"Current data: {model.as_dict}")
sys.exit(app.exec_())