我需要帮助来从QTreeView结构构建层次结构的嵌套字典,以获得类似这样的内容:
{"A": {"B": {"H": {}, "I": {"M": {}, "N": {}}}, "D": {}, "E": {}, "F": {}, "G": {"L": {}}, "C": {"J": {}, "K": {}}}}
{
"A": {
"B": {
"H": {},
"I": {
"M": {},
"N": {}
}
},
"D": {},
"E": {},
"F": {},
"G": {
"L": {}
},
"C": {
"J": {},
"K": {}
}
}
}
在这种情况下,我不使用列,并且QTreeView表示一种目录结构(我实际上是从像上面这样的字典中提取出来的,只是想在修改Tree之后重新创建字典)
我已经有这样的东西了:
def to_dict(self, _structure={}, _parent=''):
sublist[self.name()] = self._children
for child in self._children:
_structure[self.name()] = sublist
child.to_dict(_structure, self.name())
很明显self._children是一个列表,因此无法正常工作
编辑:我想我可能需要这样的东西:
def to_dict(self, _structure={}, _parent=''):
sublist = {self.name(): {}}
for child in self._children:
if _parent == '':
_structure = sublist
else:
_structure[_parent].update(sublist)
child.to_dict(_structure, self.name())
return _structure
这里的问题是...我需要在_structure字典中找到_parent键,据我所知,它将始终位于字典的最低级别...我真的需要搜索整个_structure吗? dict averytime是否想为给定的_parent添加新的下标,还是有更好的解决方案?
答案 0 :(得分:2)
要将字典转换为模型,则必须对字典进行递归迭代,然后根据数据类型将其插入模型。在相反的情况下是相同的。
from PySide import QtCore, QtGui
def fill_model_from_json(parent, d):
if isinstance(d, dict):
for k, v in d.items():
child = QtGui.QStandardItem(str(k))
parent.appendRow(child)
fill_model_from_json(child, v)
elif isinstance(d, list):
for v in d.items():
fill_model_from_json(parent, v)
else:
parent.appendRow(QtGui.QStandardItem(str(d)))
def fill_dict_from_model(parent_index, d):
v = {}
for i in range(model.rowCount(parent_index)):
ix = model.index(i, 0, parent_index)
fill_dict_from_model(ix, v)
d[parent_index.data()] = v
def model_to_dict(model):
d = dict()
for i in range(model.rowCount()):
ix = model.index(i, 0)
fill_dict_from_model(ix, d)
return d
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
tree = QtGui.QTreeView()
model = QtGui.QStandardItemModel()
data = {"A": {"B": {"H": {}, "I": {"M": {}, "N": {}}}, "D": {}, "E": {}, "F": {}, "G": {"L": {}}, "C": {"J": {}, "K": {}}}}
fill_model_from_json(model.invisibleRootItem(), data)
tree.setModel(model)
tree.expandAll()
tree.resize(360, 480)
tree.show()
d = model_to_dict(model)
assert(d == data)
print(d)
sys.exit(app.exec_())