forked from dridk/QJsonModel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqjsonmodel.py
590 lines (429 loc) · 16.6 KB
/
qjsonmodel.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
"""Python adaptation of https://github.com/dridk/QJsonModel
Supports Python 2 and 3 with PySide, PySide2, PyQt4 or PyQt5.
Requires https://github.com/mottosso/Qt.py
Usage:
Use it like you would the C++ version.
>>> import qjsonmodel
>>> model = qjsonmodel.QJsonModel()
>>> model.load({"key": "value"})
Test:
Run the provided example to sanity check your Python,
dependencies and Qt binding.
$ python qjsonmodel.py
Changes:
This module differs from the C++ version in the following ways.
1. Setters and getters are replaced by Python properties
2. Objects are sorted by default, disabled via load(sort=False)
3. load() takes a Python dictionary as opposed to
a string or file handle.
- To load from a string, use built-in `json.loads()`
>>> import json
>>> document = json.loads("{'key': 'value'}")
>>> model.load(document)
- To load from a file, use `with open(fname)`
>>> import json
>>> with open("file.json") as f:
... document = json.load(f)
... model.load(document)
"""
import json
import ctypes
from Qt import QtWidgets, QtCore, __binding__
from PySide2.QtWidgets import QApplication, QPushButton, QWidget
from PySide2.QtGui import Qt
####vymazat
from PySide2 import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
#from Qt import *
JSON_FILE="/home/pou/pyside2_python_qml/QJsonModel/asf.json"
class QJsonTreeItem(object):
def __init__(self, parent=None):
self._parent = parent
self._key = ""
self._value = ""
self._type = None
self._children = list()
def appendChild(self, item):
self._children.append(item)
def child(self, row):
return self._children[row]
def parent(self):
return self._parent
def childCount(self):
return len(self._children)
def row(self):
return (
self._parent._children.index(self)
if self._parent else 0
)
@property
def key(self):
return self._key
@key.setter
def key(self, key):
self._key = key
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
@property
def type(self):
return self._type
@type.setter
def type(self, typ):
self._type = typ
@classmethod
def load(self, value, parent=None, sort=True):
rootItem = QJsonTreeItem(parent)
rootItem.key = "root"
if isinstance(value, dict):
items = (
sorted(value.items())
if sort else value.items()
)
for key, value in items:
child = self.load(value, rootItem)
child.key = key
child.type = type(value)
rootItem.appendChild(child)
elif isinstance(value, list):
for index, value in enumerate(value):
child = self.load(value, rootItem)
child.key = str(index)
child.type = type(value)
rootItem.appendChild(child)
else:
rootItem.value = value
rootItem.type = type(value)
return rootItem
def add_child(self,parent,muj_typ):
child = QJsonTreeItem(parent)
child.key = "x"
child.value=1
child.type = muj_typ
parent.appendChild(child)
def add_item(self,key,value,parent,muj_typ):
#print("Pridavam, sibling type: "+str(sibling._type)+" value:"+str(sibling._value)+" key:"+str(sibling.key),flush=True)
#print("Pridavam, parent type: "+str(parent._type)+" value:"+str(parent._value)+" key:"+str(parent.key),flush=True)
#print("Typ je:"+str(muj_typ))
child = QJsonTreeItem(parent)
child.key = key
child.value=value
child.type = muj_typ
parent.appendChild(child)
def remove_item(self,item):
parent=item.parent()
parent._children.remove(item)
class QJsonModel(QtCore.QAbstractItemModel):
def __init__(self, parent=None):
super(QJsonModel, self).__init__(parent)
self._rootItem = QJsonTreeItem()
self._headers = ("key", "value","typ")
self._dragFrom=None
def load(self, document):
"""Load from dictionary
Arguments:
document (dict): JSON-compatible dictionary
"""
assert isinstance(document, (dict, list, tuple)), (
"`document` must be of dict, list or tuple, "
"not %s" % type(document)
)
self.beginResetModel()
self._rootItem = QJsonTreeItem.load(document,sort=False)
self._rootItem.type = type(document)
self.endResetModel()
return True
def json(self, root=None):
"""Serialise model as JSON-compliant dictionary
Arguments:
root (QJsonTreeItem, optional): Serialise from here
defaults to the the top-level item
Returns:
model as dict
"""
root = root or self._rootItem
return self.genJson(root)
def data(self, index, role):
if not index.isValid():
return None
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
if index.column() == 0:
if isinstance(item.parent().type(),list):
return str(index.row())
return item.key
if index.column() == 1:
return item.value
if index.column() == 2:
return str(item.type)
elif role == QtCore.Qt.EditRole:
if index.column() == 1:
return item.value
return None
def setData(self, index, value, role):
if role == QtCore.Qt.EditRole:
if index.column() == 1:
item = index.internalPointer()
if isinstance(item.type(), int):
try:
item.value=int(value)
except ValueError:
return False
else:
item.value = str(value)
if __binding__ in ("PySide", "PyQt4"):
self.dataChanged.emit(index, index)
else:
self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
return True
if index.column() ==0 : #editace klice
item = index.internalPointer()
if isinstance(item.parent().type(),list): ##tady nemuzu menit kdy, je to index
return False
if not self.validateKey(item,value):
return False
item.key = str(value)
if __binding__ in ("PySide", "PyQt4"):
self.dataChanged.emit(index, index)
else:
self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
return True
return False
def validateKey(self,item,new_key):
parent=item.parent()
for i in range(parent.childCount()):
if parent.child(i).key == new_key:
return False
return True
def headerData(self, section, orientation, role):
if role != QtCore.Qt.DisplayRole:
return None
if orientation == QtCore.Qt.Horizontal:
return self._headers[section]
def index(self, row, column, parent=QtCore.QModelIndex()):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self._rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parent()
if parentItem == self._rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self._rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
def columnCount(self, parent=QtCore.QModelIndex()):
return 3
def mimeTypes(self):
"""
Only accept the internal custom drop type which is plain text
"""
return [ "application/pou.cz" ]
def mimeData(self, indices):
#print("Generate mime Data - len:"+str(len(indices)),flush=True)
mimeData = QtCore.QMimeData()
encodedData = QtCore.QByteArray()
if len(indices) != 1:
return None
stream = QtCore.QDataStream(encodedData, QtCore.QIODevice.WriteOnly)
index=indices[0]
item = index.internalPointer()
#data=str(id(item))#ukazatel
data="AHOJ"
self._dragFrom=index
mimeData.setData("application/pou.cz", bytes(data, 'utf-8'))
mimeData.setText(data)
return mimeData
def dropMimeData(self, data, action, row, column, parent):
"""Nejdriv jsem do MIME dat chtel ulozit ukazatel na QJsonTreeItem
(QAbstracItemINDEX jsem nemohl ulozit protoze obejkt zanikne hned za funkci mimeData() )
to jako funguje dobre - musim samozrejmne zarucit ze ukazatel bude platny,
ale pro bezpecnost kodu jsem se rozhodl vyuzit k tomuto globalni funkci _dragFrom - ktera reprezentuje onen QAbstracItemINDEX
toto by melo byt bezpecnejsi a cistci - i kdyz prihlednu k dedeni"""
#item_src=ctypes.cast(int(data.text()), ctypes.py_object).value
item_src=parent_test=self._dragFrom.internalPointer()
parent_src=item_src.parent()
parent=parent.internalPointer()
#print("DROPING r:"+str(row)+" c:"+str(column)+" to:"+str(parent_src.row())+" action:"+str(action),flush=True)
#print("DROP: from:"+str(parent_src._children.index(item_src)),flush=True)
print("Parent1: "+str(id(parent_src))+" parent2: "+str(id(parent))+" paretn3: "+str(id(parent_test)),flush=True)
return False
def supportedDropActions(self):
return Qt.MoveAction|Qt.CopyAction;
def supportedDragActions(self):
return Qt.MoveAction|Qt.CopyAction
def flags(self, index):
flags = super(QJsonModel, self).flags(index)
if index.column() == 1:
return QtCore.Qt.ItemIsEditable | flags
elif index.column() == 0:
flags=flags | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled
return QtCore.Qt.ItemIsEditable | flags
else:
return flags
def genJson(self, item):
nchild = item.childCount()
if item.type is dict:
document = {}
for i in range(nchild):
ch = item.child(i)
document[ch.key] = self.genJson(ch)
return document
elif item.type == list:
document = []
for i in range(nchild):
ch = item.child(i)
document.append(self.genJson(ch))
return document
else:
return item.value
def appendItem(self,parent,type,key="",value="novy_klic"):
self.beginInsertRows(parent,parent.row(),parent.row())
self._rootItem.add_item(key,value,parent.internalPointer(),type)
#self.refresh();
self.endInsertRows()
def appendItem2(self,parent,item):
self.beginInsertRows(parent,parent.row(),parent.row())
parent.internalPointer().appendChild(item)
self.endInsertRows()
def removeItem(self,item):
self.beginRemoveRows(item.parent(),item.row(),item.row()+1)
self._rootItem.remove_item(item.internalPointer())
self.endRemoveRows()
def refresh(self):
if __binding__ in ("PySide", "PyQt4"):
self.layoutChanged.emit()
else:
self.layoutChanged.emit()
#self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
def get_item_level(self,model_index):
level=0
parent=model_index.parent()
while parent.isValid() :
parent=parent.parent()
level=level+1
return level
class JsonWidget(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.button = QtWidgets.QPushButton("Save")
self.treeView = QtWidgets.QTreeView()
self.model = self.Init_data_model()
self.treeView.setModel(self.model)
##DRAG and DROP neni implementovano v modelu
self.treeView.setDragDropMode(QAbstractItemView.InternalMove);
self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection);
self.treeView.setDragEnabled(True);
self.treeView.setAcceptDrops(True);
self.treeView.setDropIndicatorShown(True);
header = self.treeView.header()
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
header.setStretchLastSection(False)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
with open(JSON_FILE) as f:
document = json.load(f)
self.model.load(document)
self.button.clicked.connect(self.Save_to_file)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.treeView)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
#self.treeView.doubleClicked.connect(self.on_doubleClicked)
self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)
self.treeView.customContextMenuRequested.connect(self.openMenu)
def Init_data_model(self):
return QJsonModel()
def Save_to_file(self):
data=self.model.json()
print("Saving....",flush=True)
#print(data,flush=True)
with open(JSON_FILE, 'w') as f:
json.dump(data, f)
@QtCore.Slot("QModelIndex")
def on_doubleClicked(self, ix):
#print(ix.data())
print("Double clicked",flush=True)
def openMenu(self, position):
#print("menu:"+str(position),flush=True)
selected_item = self.treeView.indexAt(position)
if not selected_item.isValid():
print("no selected",flush=True)
return
selected_type=selected_item.internalPointer().type()
menu = QMenu()
menu.addAction(self.tr("Add int"),self.add_int_item)
menu.addAction(self.tr("Add str"),self.add_str_item)
menu.addAction(self.tr("Add list"),self.add_list_item)
menu.addAction(self.tr("Add dict"),self.add_dict_item)
if isinstance(selected_type,list) or isinstance(selected_type,dict):
menu.addAction(self.tr("Add child"),self.add_child_item)
menu.addAction(self.tr("Remove item"),self.remove_item)
menu.exec_(self.treeView.viewport().mapToGlobal(position))
def add_item(self,type,key="",value="",child=False):
selected_index=self.treeView.selectedIndexes()
if len(selected_index) <= 0:
raise Exception('Row not selected')
item=selected_index[0]
if child:
item=item.parent()
self.model.appendItem(item,type,key,value)
def remove_item(self):
selected_index=self.treeView.selectedIndexes()
if len(selected_index) <= 0:
raise Exception('Row not selected')
self.model.removeItem(selected_index[0])
def add_int_item(self):
self.add_item(int)
def add_str_item(self):
self.add_item(str)
def add_list_item(self):
self.add_item(list)
def add_dict_item(self):
self.add_item(dict)
def add_child_int_item(self):
self.add_item(int,child=True)
def add_child_str_item(self):
self.add_item(str,child=True)
def add_child_list_item(self):
self.add_item(list,child=True)
def add_child_dict_item(self):
self.add_item(dict,child=True)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = QWidget()
#model.load(document)
#model.clear()
#model.load(document)
# Sanity check
#assert (
# json.dumps(model.json(), sort_keys=True) ==
# json.dumps(document, sort_keys=True)
#)
layout = QtWidgets.QVBoxLayout()
jsonwidget= JsonWidget();
layout.addWidget(jsonwidget)
window.setLayout(layout)
window.show()
window.resize(500, 300)
app.exec_()