如何获取所有树项的已检查状态,并将它们存储回self._data?
我使用此数据结构填充树
{
"camera": {
"ver": 8,
"new_ver": 10
},
"char": {
"bob": {
"ver": 2,
"new_ver": 20
},
"aston": {
"ver": 4,
"new_ver": 13
}
}
}
代码是
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
import os
# enable ctrl-c to kill the app
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
import json
from pprint import pprint
from collections import OrderedDict
data_dict = OrderedDict([('camera', OrderedDict([('ver', '8'), ('new_ver', '10')])),
('char',
OrderedDict([
('bob', OrderedDict(
[('ver', '2'), ('new_ver', '20')])),
('aston', OrderedDict(
[('ver', '4'), ('new_ver', '13')]))
]))
])
pprint(data_dict)
class AssetModel(QStandardItemModel):
def __init__(self):
super(AssetModel, self).__init__()
self._data = data_dict
# def data(self, index, role=Qt.DisplayRole):
# if index.isValid():
# if role == Qt.DisplayRole:
# def setData(self, index, value, role=Qt.EditRole):
# print 'in setData'
# if index.isValid():
# print 'index:',index.row(),'value:',value.toPyObject(),role
# if index.row()==0 and role==Qt.CheckStateRole:
# # self.dataChanged.emit(index, index)
# print 'need to update self._data'
# return True
# return False
class MyWindow(QDialog):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
layout = QVBoxLayout()
self.treeView = QTreeView()
self.model = AssetModel()
self.treeView.setModel(self.model)
self.button = QPushButton('Print')
layout.addWidget(self.treeView)
layout.addWidget(self.button)
self.setLayout(layout)
self.initialLoad()
self.button.clicked.connect(self.get_data)
def initialLoad(self):
# self.model.load()
self.resize(400, 300)
self.populateTree()
def populateTree(self):
for k in data_dict.keys():
parent1 = QStandardItem(k)
parent1.setCheckable(True)
if k == 'char':
for j in data_dict[k].keys():
char_name = QStandardItem(j)
char_name.setCheckable(True)
ver_data = data_dict[k][j].values()
children = [QStandardItem(x)
for x in ver_data]
if int(ver_data[0]) < int(ver_data[1]):
char_name.setCheckState(Qt.Checked)
parent1.setCheckState(Qt.Checked)
parent1.appendRow([char_name] + children)
self.model.appendRow(parent1)
else:
ver_data = data_dict[k].values()
children = [QStandardItem(x) for x in ver_data]
self.model.appendRow([parent1]+children)
if int(ver_data[0]) < int(ver_data[1]):
parent1.setCheckState(Qt.Checked)
self.headers = ['asset', 'ver', 'new_ver']
self.model.setHorizontalHeaderLabels(self.headers)
self.treeView.expandAll()
for i in range(len(self.headers)):
self.treeView.resizeColumnToContents(i)
def get_data(self):
# print the data shown on tree
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
预期的结果是当你点击按钮时,它打印出这个结构:假设相机和bob被选中,aston未经检查
{
"camera": {
"ver": 8,
"new_ver": 10,
"checked":1
},
"char": {
"bob": {
"ver": 2,
"new_ver": 20,
"checked":1
},
"aston": {
"ver": 4,
"new_ver": 13,
"checked":0
}
}
}
我应该迭代树视图来获得结果吗?
答案 0 :(得分:0)
只有通过迭代,以递归方式实现它。 直接处理模态,而不是视图。