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.