我希望能够在 QTreeView 中展开或折叠特定分支的所有子项。我正在使用 PyQt4。
我知道 QTreeView 有一个绑定到 * 的扩展所有子项功能,但我需要两件事:它需要绑定到不同的组合键(shift-space),我还需要能够折叠所有子项.
这是我到目前为止所尝试的:我有一个 QTreeView 的子类,其中我正在检查 shift-space 键组合。我知道 QModelIndex 会让我用“child”功能选择一个特定的孩子,但这需要知道孩子的数量。我可以通过查看 internalPointer 来计算孩子的数量,但这只能为我提供层次结构第一级的信息。如果我尝试使用递归,我可以获得一堆子计数,但是我不知道如何将这些转换回有效的 QModelIndex。
这是一些代码:
def keyPressEvent(self, event):
"""
Capture key press events to handle:
- enable/disable
"""
#shift - space means toggle expanded/collapsed for all children
if (event.key() == QtCore.Qt.Key_Space and
event.modifiers() & QtCore.Qt.ShiftModifier):
expanded = self.isExpanded(self.selectedIndexes()[0])
for cellIndex in self.selectedIndexes():
if cellIndex.column() == 0: #only need to call it once per row
#I can get the actual object represented here
item = cellIndex.internalPointer()
#and I can get the number of children from that
numChildren = item.get_child_count()
#but now what? How do I convert this number into valid
#QModelIndex objects? I know I could use:
# cellIndex.child(row, 0)
#to get the immediate children's QModelIndex's, but how
#would I deal with grandchildren, great grandchildren, etc...
self.setExpanded(cellIndex, not(expanded))
return
这是我正在调查的递归方法的开始,但是在实际尝试设置展开状态时我遇到了困难,因为一旦进入递归,我就失去了与任何有效 QModelIndex 的“联系”......
def toggle_expanded(self, item, expand):
"""
Toggles the children of item (recursively)
"""
for row in range(0,item.get_child_count()):
newItem = item.get_child_at_row(row)
self.toggle_expanded(newItem, expand)
#well... I'm stuck here because I'd like to toggle the expanded
#setting of the "current" item, but I don't know how to convert
#my pointer to the object represented in the tree view back into
#a valid QModelIndex
#self.setExpanded(?????, expand) #<- What I'd like to run
print "Setting", item.get_name(), "to", str(expand) #<- simple debug statement that indicates that the concept is valid
感谢大家花时间看这个!