当用户单击刷新按钮重新创建模型时,如何存储并还原展开的项。我希望递归地存储用户选择和所有展开的项,然后填充模型,最后还原展开的项和选定的项
我已经能够找出如何恢复选择,但我不知道如何存储/恢复扩展的项目。这可以使用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_())
目前没有回答
相关问题 更多 >
编程相关推荐