好吧……兄弟姐妹实际上并没有带我去我想去的地方。我设法让代码按如下方式工作(这似乎是一个不错的实现)。仍然要感谢 Ebral 教授,他让我沿着兄弟姐妹的想法走上了正确的道路(事实证明我需要使用 QModelIndex.child(row, column) 并从那里递归迭代)。
请注意,代码中有以下假设:它假设您的基础数据存储对象能够报告它们有多少个子对象(在我的代码中为 get_child_count() )。如果不是这种情况,您将不得不以不同的方式获得子计数...也许只是任意尝试获取子索引 - 使用 QModelIndex.child(row, col) - 行数不断增加直到您返回无效索引? - 这是 Ebral 教授的建议,我可能仍然会尝试(只是我已经有了一种简单的方法来通过从我的数据存储请求来获取子计数)。
另请注意,我实际上根据是展开还是折叠在递归中的不同点展开/折叠每个节点。这是因为,通过反复试验,我发现如果我只在代码中的一处执行动画树视图,动画树视图就会卡顿和弹出。现在,通过根据我是否位于顶层(即我正在影响的分支的根 - 而不是整个树视图的根)来反转我执行此操作的顺序,我得到了一个非常流畅的动画。下面记录了这一点。
以下代码位于 QTreeView 子类中。
#---------------------------------------------------------------------------
def keyPressEvent(self, event):
if (event.key() == QtCore.Qt.Key_Space and self.currentIndex().column() == 0):
shift = event.modifiers() & QtCore.Qt.ShiftModifier
if shift:
self.expand_all(self.currentIndex())
else:
expand = not(self.isExpanded(self.currentIndex()))
self.setExpanded(self.currentIndex(), expand)
#---------------------------------------------------------------------------
def expand_all(self, index):
"""
Expands/collapses all the children and grandchildren etc. of index.
"""
expand = not(self.isExpanded(index))
if not expand: #if collapsing, do that first (wonky animation otherwise)
self.setExpanded(index, expand)
childCount = index.internalPointer().get_child_count()
self.recursive_expand(index, childCount, expand)
if expand: #if expanding, do that last (wonky animation otherwise)
self.setExpanded(index, expand)
#---------------------------------------------------------------------------
def recursive_expand(self, index, childCount, expand):
"""
Recursively expands/collpases all the children of index.
"""
for childNo in range(0, childCount):
childIndex = index.child(childNo, 0)
if expand: #if expanding, do that first (wonky animation otherwise)
self.setExpanded(childIndex, expand)
subChildCount = childIndex.internalPointer().get_child_count()
if subChildCount > 0:
self.recursive_expand(childIndex, subChildCount, expand)
if not expand: #if collapsing, do it last (wonky animation otherwise)
self.setExpanded(childIndex, expand)