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.

Jan
  • 171
  • 8

3 Answers3

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.

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
Joseph
  • 75,746
  • 7
  • 171
  • 282
  • 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 '20 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 '20 at 15:36
5

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!

Jan
  • 171
  • 8
  • 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: https://gis.stackexchange.com/questions/318842/load-ascii-rasters-in-qgis-as-singleband-pseudocolor-by-default/319033#319033 – Jan Apr 18 '19 at 08: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 08: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 '20 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

Fran Raga
  • 7,838
  • 3
  • 26
  • 47
  • I tested using QGIS 2.18 and got the following error: "Traceback (most recent call last): File "", line 1, in 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 08: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 08: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 09: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