当用户单击重新创建模型的刷新按钮时,如何存储然后恢复展开的项目。我想递归存储用户选择和所有扩展项,然后填充模型,最后恢复扩展项和所选项。
我已经能够弄清楚如何还原选择,但是我不确定如何存储/还原扩展项。可以使用qstandardItemModel's match
功能来完成吗?
是否有可能改善所选项目的还原,这样就不会在每次选择项目时都触发选择更改。我想一次选择它们。
from PySide import QtGui, QtCore
class Main(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(300,500)
self.button = QtGui.QPushButton('Refresh')
self.model = QtGui.QStandardItemModel()
self.proxy = QtGui.QSortFilterProxyModel()
self.proxy.setSourceModel(self.model)
self.treeview = QtGui.QTreeView()
self.treeview.setModel(self.proxy)
self.treeview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.treeview.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.selectionModel = self.treeview.selectionModel()
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.button)
self.layout.addWidget(self.treeview)
self.setLayout(self.layout)
self.button.clicked.connect(self.populate)
# begin
self.populate()
self.treeview.expandAll()
def fill_model_from_json(self, parent, d):
if isinstance(d, dict):
for k, v in d.items():
child = QtGui.QStandardItem(str(k))
parent.appendRow(child)
self.fill_model_from_json(child, v)
elif isinstance(d, list):
for v in d:
self.fill_model_from_json(parent, v)
else:
parent.appendRow(QtGui.QStandardItem(str(d)))
def populate(self):
# Store User Selection
names = [x.data() for x in self.selectionModel.selectedRows()]
self.selectionModel.clearSelection()
# Store Expanded Items
# Populate
self.model.clear()
self.model.setHorizontalHeaderLabels(['Name'])
items = {
'Pasta': {
'Spaghetti': {
'Thick': {},
'Thin': {}
},
'Ravioli': {
'Mushroom': {},
'Plain': {},
},
},
'Cookies': {
'Chocolate': {
'Dark Chocolate': {},
'Milk Chocolate': {}
},
'Misc': {
'M&M\'s': {},
'Snickerdoodle': {},
},
},
'Hummus': {
'Plain': {},
'Spicy': {},
'Mild': {}
}
}
self.fill_model_from_json(self.model.invisibleRootItem(), items)
# Restore User Selection
indexes = []
for x in names:
results = self.model.match(self.model.index(0, 0), QtCore.Qt.DisplayRole, x, -1, QtCore.Qt.MatchRecursive)
indexes.extend(results)
for x in indexes:
idx = self.proxy.mapFromSource(x)
self.selectionModel.select(idx, QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows)
# Restore Expanded Items
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())