QTreeViewの特定のブランチのすべての子を展開または折りたたむことができるようにしたいと思います。私はPyQt4を使用しています。
QTreeViewには*にバインドされたすべての子の展開機能があることは知っていますが、2つのことが必要です。別のキーの組み合わせ(シフトスペース)にバインドする必要があり、すべての子も折りたたむことができる必要があります。 。
これまでに試したことは次のとおりです。QTreeViewのサブクラスがあり、シフトスペースキーの組み合わせをチェックしています。QModelIndexで「子」関数を使用して特定の子を選択できることは知っていますが、それには子の数を知る必要があります。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
これを見てくれてありがとう!