You can use the sortChildren
method of QTreeWidgetItem(s) like this:
sort_column = 1
# Iterate top-level elements
for index in range(tree.topLevelItemCount()):
# Obtain the actual top-level item
top_level_item = tree.topLevelItem(index)
# Sort
top_level_item.sortChildren(sort_column)
Notice that if you add new children to an item you need to sort it again (only the changed item)
EDIT
Thanks, that's a step in the right direction, but the question now is how to override the default sort behavior. I'm doing self.treeWidget.header().sortIndicatorChanged.connect(self.sortChanged), but since that's a signal it just triggers after the widget does its regular sort, so in the end it has no effect - the top level items get sorted before the function is called
Unless you go for a custom model/view, you may try two approaches (I don't have tested them):
1. Override the "sorting" method of the QTreeWidget
try to replace the sortItems()
method with some no-op, but probably the widget have other private methods that are called internally.
2. Override the root-item sortChildren()
It's possible that the sorting is implemented calling the (hidden) root-item sortChildren(), that will sort the top-level-items and call the sortChildren() of those. You may be able to figure out how to get/set this item using rootIndex()
/setRootIndex()
and then override the sort method (e.g. root.sortChildren = lambda c, o: None
).