我想使用递归构造一个包含几个家族世代级别的JSON文件的QTreeWidget。这是我的代码:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets
from PyQt5 import QtCore
import json
#read in JSON family structure
def readJsonData(fileName):
with open(fileName) as json_data:
treeData = json.load( json_data )
return treeData
fileName = 'family.json'
d = readJsonData(fileName)
myList = []
def myprint( d, myList ):
for k, v in d.items():
if isinstance(v, dict):
myprint(v, myList )
myList.append(k)
else:
myList.append(k)
return myList
a = myprint(d, myList )
class MyMainWindow(QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.tree = QTreeWidget(self)
self.tree.setSelectionMode(QAbstractItemView.SingleSelection)
editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree)
self.setCentralWidget(self.tree)
self.tree.setHeaderLabel('Tree')
i = QTreeWidgetItem(self.tree, [a[len(a)-1]])
a.pop()
self.tree.addTopLevelItem(i)
for x in a:
QTreeWidgetItem(i, ['{}'.format(x)])
if __name__ == "__main__":
app = QApplication(sys.argv)
ui = MyMainWindow()
ui.show()
sys.exit(app.exec_())
这将创建一个主树,其根mainMenu及其成员为:
['grandChild12',
'grandChild11',
'Child1',
'grandChild21',
'grandChild22',
'Child2',
'grandChild31',
'grandChild32',
'Child3']
但是,结果应该像JSON文件结构一样嵌套:
'mainMenu':
'Child1'
'grandChild11'
'grandChild12'
'Child2'
'grandChild21'
'grandChild22'
'Child3'
'grandChild31'
'grandChild32'
我如何适应这一行:
for x in a:
QTreeWidgetItem(i, ['{}'.format(x)])
创建具有递归的正确结构?我以前在Java中已经做过此事,所以我知道可以通过从主干的左,中或右上走到肢体到节点再到末端叶子的方式来完成。
JSON文件显示如下:
{
"mainMenu": {
"Child1": {
"grandChild11": "None",
"grandChild12": "None"
},
"Child2": {
"grandChild21": "None",
"grandChild22": "None"
},
"Child3": {
"grandChild31": "xx",
"grandChild32": "xy"
}
}
}