Skip to content

feat(tree): implement sortData and sortKey#560

Open
slook wants to merge 2 commits intoceccopierangiolieugenio:mainfrom
slook:tree-sortkey
Open

feat(tree): implement sortData and sortKey#560
slook wants to merge 2 commits intoceccopierangiolieugenio:mainfrom
slook:tree-sortkey

Conversation

@slook
Copy link
Copy Markdown
Contributor

@slook slook commented Dec 22, 2025

TTkTreeWidget() and TTkTreeWidgetItem():

  • Added: sortKey() and sortData() to provide custom values to the key argument of the internal sort() function.
  • Added: Optional key keyword argument for sortChildren(). None fall-back to the simple character-based sorting.
  • Fixed: Use plaintext strings instead of ANSI codes in TTkString() objects to sort items where no custom key is specified.

TTkFileTreeWidget() and TTkFileTreeWidgetItem():

  • Added: Natural sorting of folders and files using _raw data values which were stored but hadn't been implemented yet.
  • Changed: sortData() in FileTreeWidgetItem now returns List instead of str type.
  • Fixed: Sort all FileTreeWidgetItem items after populating the widget instead of sorting every row after each insertion which was causing a very large performance impact while listing large folders after enabling a sort column.

Folders are always grouped at the top (regardless of the direction of the sort order), including inside expanded children:
image image
Sorting by "Size" uses the _raw values in the FileTreeWidgetItem to give natural sorting order ^^

The file and folder items are now always grouped at the top and the proper numeric values cause the items to be displayed in a much more logical manor that makes navigating a filesystem work more like one would reasonably expect. It is a good example of the reason why such an implementation is desirable. The documentation strings explain how to implement it for any purpose.

The default behaviour of TTkTree is unchanged, you have to override the sortKey() or sortData() in a sub-class to get some other values to use as the key to do custom sorting strategies. The advantage of allowing Any type of value (or tuple of values) to be returned by sortKey() is that any complexity of multi-factor ordering can be sorted() in a single pass.


Note: AI (Cognition) wrote the regex used for alphanumeric splitting and a human (me) implemented the sorting with reference to the Python docs sorted() and https://docs.python.org/3/howto/sorting.html#sortinghowto

@slook
Copy link
Copy Markdown
Contributor Author

slook commented Dec 22, 2025

Pushed a change only to clarify the docstrings but did not make any changes to the code. If not deemed suitable for merging then it is open for suggestions or other ideas to be taken from it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant