Sort layers in table of contents in QGIS 3?

You could use the following to sort all loaded layers alphabetically:

from collections import OrderedDict
root = QgsProject.instance().layerTreeRoot()
LayerNamesEnumDict=lambda listCh:{listCh[q[0]].name()+str(q[0]):q[1]
                                   for q in enumerate(listCh)}

mLNED = LayerNamesEnumDict(root.children())
mLNEDkeys = OrderedDict(sorted(LayerNamesEnumDict(root.children()).items())).keys()

mLNEDsorted = [mLNED[k].clone() for k in mLNEDkeys]
root.insertChildNodes(0,mLNEDsorted)
for n in mLNED.values():
    root.removeChildNode(n)

Credit to @MikhailMinin with his Sort Layers plugin in which the above code is based.


Another way to load and sort a lot of layers into QGIS 3 is using the "Load Them All" plugin: "recursively loads vector and raster layers stored in a directory structure, based on several filters". One of the options is to sort the loaded layers by name! Perfect!


For load using ascening order you only need this (sortByColumn method):

view = iface.layerTreeView()
view.setSortingEnabled(True)
view.sortByColumn(0, Qt.AscendingOrder) # sort first column (Qt.DescendingOrder to reverse)

Add after load some layers,you will see that they are loaded correctly ordered.

tested using QGIS 3.6.1

I hope this helps