6

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.

6

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.

| improve this answer | |
  • 1
    This works for me (QGIS 3.10.3-A Coruña) but only for top level Layers in the Layers panel. For child Layers (e.g., Layers inside a Group), they remain unsorted. Any tips on how to tweak the code to sort recursively? – davidafuller01 Mar 12 at 16:17
  • @davidafuller01 - I would suggest you ask this as a new question. It could be that there's an existing function or plugin which achieves this. – Joseph Mar 16 at 15:36
3

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!

| improve this answer | |
  • The only thing I still miss is the option to load the raster layers as singleband pseudocolor with different color maps and min/max values set to actual min/max of the raster. see: gis.stackexchange.com/questions/318842/… – Jan Apr 18 '19 at 8:05
  • 1
    This answer actually solved the original question: the plugin loads a lot of layers in alphabetical order. Why does this answer get downvoted? – Jan Apr 18 '19 at 8:20
  • For reference, I think what you missed in your comment (it was last year) is already implemented in Load Them All. See load rasters with predefined style. – Germán Carrillo Jun 16 at 19:18
2

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

| improve this answer | |
  • I tested using QGIS 2.18 and got the following error: "Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'Qt' is not defined" I got no error when I included the import code from the original code. But then the code did not sort the layers in the TOC. – Jan Apr 16 '19 at 8:50
  • I tested also in QGIS 3.4.6: I got no errors, but the code did not sort the layers that were already in the TOC, and neither layers that were added afterwards. – Jan Apr 16 '19 at 8:51
  • Your question is about qgis 3,no qgis 2.18!this code short layer on toc,you need execute and after add layers!Clean toc,execute and add layers – Fran Raga Apr 16 '19 at 9:54
  • I also tried in Qgis 3.4.6, but it doesn't seem to work. I run the code in the python console. Then I add 3 layers (3 ascii rasters) and they are added in reversed alphabetical order in the TOC. – Jan Apr 16 '19 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.