This does not seem to be possible at all just yet. There is discussions about this issue in various places, for instance here in the bug tracker. Using Python I also have not seen a way of doing this just yet. The sorting simply relates to the time at which a collection has been linked to the scene, and cannot really be changed.
The underlying issue seems to be that at the time of writing this, the relevant Python methods to sort are not implemented for collections. In Python, you'll need to implement at least code for the hidden __lt__
(less than), __gt__
(greather than), maybe also the __eq__
(is equal to) functions. Those functions are called when you do comparisons like A > B
or A == B
, see this for further reference. Furthermore, for sorting, they are the base for the comparison itself. When you sort someting complex like a collection object, which has many attributes, Python needs to be told what makes one collection "bigger" or "smaller" than the other. Obviously you want the name, but Python-wise you could also aim at an index, a hash, a postal code, or whatever. That's why those methods exist, in them you tell Python based on what >
or <
operate.
Now when you test this in Python, you can try these three examples. I am retrieving collection lists in various places and ask Python to sort them using the sorted()
function:
sorted(bpy.data.collections)
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
TypeError: '<' not supported between instances of 'Collection' and 'Collection'`
The error thrown indicated that the __lt__
method has no code behind.
same of course with the keys()
attribute:
sorted(bpy.data.collections.values())
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
TypeError: '<' not supported between instances of 'Collection' and 'Collection'
We can also test this for the LayerCollection
type, which is what you see in reality in the outliner:
sorted(bpy.context.view_layer.active_layer_collection.children)
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
TypeError: '<' not supported between instances of 'LayerCollection' and 'LayerCollection'
The error in all cases remains the same. So what I'm aiming at with the explanation here is that sorting simply isn't implemented yet, and you can't really force it to happen from the Python side. You would probably need to unlink all collections from the scene first and relink them again in a defined order to enforce a sorted result. But since Collections can have nesting and multiple parents, this can become quite tricky.