我目前正在使用下面的代码在模型树中选择多行。 但是在拥有大量节点的大型会话中,它可能会非常慢。 我怀疑这不是很有效,因为它可能是逐个选择行。有没有什么可以加快速度 - 例如,在选择直到最后一个或在一个电话中选择全部时不刷新?
selectionModel = self.tree.selectionModel()
selectionModel.clear()
for node, i in self.tree.model().iterNodeAndIndexs():
if nodeCondition:
selectionModel.select(i, selectionModel.Select | selectionModel.Rows)
答案 0 :(得分:2)
如Model/View Programming Guide中所述,您可以将左上角和右下角的索引放在QItemSelection
中,然后一次选择所有单元格。
请注意,对于分层模型,您必须以递归方式在树的所有级别进行选择(请参阅selecting all notes section)。像这样:
def mySelectRows(treeView, parentIndex=None, topRow=0, bottomRow=None):
if parentIndex is None:
parentIndex = QtCore.QModelIndex()
model = treeView.model()
totalSelection = QtGui.QItemSelection()
def populateSelection(parentIndex, topRow=0, bottomRow=None):
if bottomRow is None:
bottomRow = model.rowCount(parentIndex)
leftCol, rightCol = 0, model.columnCount(parentIndex)
topLeft = model.index(topRow, leftCol, parentIndex)
bottomRight = model.index(bottomRow-1, rightCol-1, parentIndex)
newSelection = QtGui.QItemSelection(topLeft, bottomRight)
totalSelection.merge(newSelection, QtGui.QItemSelectionModel.Select)
for row in range(topRow, bottomRow):
childIndex = model.index(row, 0, parentIndex)
if model.rowCount(childIndex) > 0:
populateSelection(childIndex)
# Start recursion
populateSelection(parentIndex, topRow=topRow, bottomRow=bottomRow)
selectionModel = treeView.selectionModel()
selectionModel.select(totalSelection,
QtGui.QItemSelectionModel.ClearAndSelect)
根据您对模型的实施情况,将if model.rowCount(childIndex) > 0
替换为if model.hasChildren(childIndex)
可能会更快