大树中最有效的PyQt模型选择 [英] Most efficient PyQt Model selection in big trees

查看:87
本文介绍了大树中最有效的PyQt模型选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码在模型树中选择多行. 但是在有节点负载的大型会话中,这可能确实很慢. 我怀疑这不是很有效,因为它可能会一一选择行.有什么可以加快处理速度的-例如,在选择直到最后一个呼叫或一次呼叫全部选择时不刷新吗?

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)

推荐答案

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)

根据模型的实现,将if model.rowCount(childIndex) > 0替换为if model.hasChildren(childIndex)

Depending on your implementation of the model it may be faster to replace if model.rowCount(childIndex) > 0 with if model.hasChildren(childIndex)

这篇关于大树中最有效的PyQt模型选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆