问题
I do not understand why this does not seem to expand the top-level root items in a QTreeView:
# clear existing treeview data
model = self.treeview.model().sourceModel()
model.clear()
# add treeview items here
# expand root level items
root = model.invisibleRootItem()
index = root.index()
for i in range(root.rowCount()):
item = model.indexFromItem(model.item(i,0))
self.treeview.expand(item)
self.treeview.setExpanded(item, True)
print 'expanded'
回答1:
If you're using a proxy model, you must use the indexes it provides, rather than the ones from the source model. So either do this:
proxy = self.treeview.model()
for row in range(proxy.rowCount()):
index = proxy.index(row, 0)
self.treeview.expand(index)
or this:
proxy = self.treeview.model()
model = proxy.sourceModel()
for row in range(model.rowCount()):
index = model.index(row, 0)
self.treeview.expand(proxy.mapFromSource(index))
来源:https://stackoverflow.com/questions/47596847/how-to-expand-top-level-qtreeview-items