问题
I'm currently selecting multiple rows in a model tree with the code below. But it can be really slow in big sessions with loads of nodes. I suspect this is not very efficient as it's probably selecting the rows one by one. Is there anything that could speed things up - for example don't refresh while selecting until the last one or select all in one call?
selectionModel = self.tree.selectionModel()
selectionModel.clear()
for node, i in self.tree.model().iterNodeAndIndexs():
if nodeCondition:
selectionModel.select(i, selectionModel.Select | selectionModel.Rows)
回答1:
As described in the Model/View Programming Guide you can put the top-left and bottom-right indices in a QItemSelection
and so select all cells at once.
Note that for hierarchical models you will have to make the selection at all levels of the tree recursively (see the selecting all notes section). Something like this:
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)
Depending on your implementation of the model it may be faster to replace if model.rowCount(childIndex) > 0
with if model.hasChildren(childIndex)
来源:https://stackoverflow.com/questions/30294933/most-efficient-pyqt-model-selection-in-big-trees