我最近在一个正在研究的项目中使用了PyQt.我有一个QTreeView连接到QAbstractItemModel,它通常有数千个节点.到目前为止,它工作正常,但我今天意识到选择很多节点非常慢.经过一番挖掘后,事实证明QAbstractItemModel.parent()经常被调用.我创建了最少的代码来重现问题:
#!/usr/bin/env python
import sys
import cProfile
import pstats
from PyQt4.QtCore import Qt, QAbstractItemModel, QVariant, QModelIndex
from PyQt4.QtGui import QApplication, QTreeView
# 200 root nodes with 10 subnodes each
class TreeNode(object):
def __init__(self, parent, row, text):
self.parent = parent
self.row = row
self.text = text
if parent is None: # root node, create subnodes
self.children = [TreeNode(self, i, unicode(i)) for i in range(10)]
else:
self.children = []
class TreeModel(QAbstractItemModel):
def __init__(self):
QAbstractItemModel.__init__(self)
self.nodes = [TreeNode(None, i, unicode(i)) for i in …Run Code Online (Sandbox Code Playgroud) 我是(Py)Qt新手,现在将C#GUI代码移植到Qt几天.我一直在问自己的一个问题是为什么QAbstractItemModel子类需要提供一个parent()方法,为什么它们需要在结果QModelIndex中提供父类中的子行?
这一要求迫使我在我的树数据添加另一层(因为我不想打电话给我们indexOf(item)的parent(),它不会是非常有效的)可以记住排索引.
我问这个是因为这是我第一次看到基于模型的视图需要这个.例如,NSOutlineViewDataSource在Cocoa中不需要这样.
Trolltech开发人员很聪明,所以我确信这是有充分理由的,我只是想知道是什么原因.