I can show and edit a json file in QTreeWidget form. How can I save this edited json file again on desktop.
my goal is to create a json editor that we can edit
import json
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class ViewTree(QTreeWidget):
def __init__(self, value):
super().__init__()
def fill_item(item, value):
def new_item(parent, text, val=None):
child = QTreeWidgetItem([text])
child.setFlags(child.flags() | Qt.ItemIsEditable)
fill_item(child, val)
parent.addChild(child)
child.setExpanded(True)
if value is None: return
elif isinstance(value, dict):
for key, val in sorted(value.items()):
new_item(item, str(key), val)
elif isinstance(value, (list, tuple)):
for val in value:
text = (str(val) if not isinstance(val, (dict, list, tuple))
else '[%s]' % type(val).__name__)
new_item(item, text, val)
else:
new_item(item, str(value))
fill_item(self.invisibleRootItem(), value)
if __name__ == '__main__':
app = QApplication([])
fname = QFileDialog.getOpenFileName()
json_file=open(fname[0],"r")
file=json.load(json_file)
window = ViewTree(file)
window.setGeometry(300, 100, 900, 600)
window.show()
app.exec_()
Okay I did not have a Json File handy to test this with but I took your code and transformed it some. Now you are dealing with a JsonTable along with your TreeWidget when you make any changes in your TreeWidget you simply update your JsonTable with those changes. This code is not complete and you will still have to render some of the sections on your own but it should give you a solid template to build from as well as a few nifty features you might not have been aware of ;)
As a final note I did not test/validate your code as I assumed you understood what it does and will understand how to tweak it should it need tweaked to work with this framework