QGIS 3 Layers – How to Sort Layers in Table of Contents in QGIS 3

layerspyqgis-3qgis-3table of contents

When I load a bunch of layers into QGIS, they seem to load in reverse alphabetical order. I'd like to sort them alphabetically.

In this thread a solution is proposed, but that does not work in QGIS 2.18 or 3.4:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.utils import iface


mw = iface.mainWindow()
lgd = mw.findChild(QTreeWidget, "theMapLegend")  # get ref to object by type/objectName
lgd.sortItems(0, Qt.AscendingOrder)  # sort first column (Qt.DescendingOrder to reverse)

How can I do this in QGIS 3?
I tried:

from qgis.PyQt.QtCore import * 
from qgis.PyQt.QtGui import *
from qgis.utils import iface

mw = iface.mainWindow()
lgd = mw.findChild(QTreeView, 'theLayerTreeView')
lgd.sortItems(0, Qt.AscendingOrder)

It "works" until the last line, then I get the error:

Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
AttributeError: 'QgsLayerTreeView' object has no attribute 'sortItems'

I don't know where to search for a method that will sort the layers as in the first code example.

Best Answer

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.