4

After running a longer script (Qgis Console), all I want to do is sort the layers within my groups; since some of them are buffers and the 'biggest' buffer is now on top.

I've tried stuff based on: Post on how to sort Layers

And Martin Dobias's post concerning the tree layer api: Layer Tree API 1 ; Layer Tree API 2 ; Layer Tree API 3

It sounds simple enough but for some reason I can not figure it out...

Among many things I've tried this:

root = QgsProject.instance().layerTreeRoot()
for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
      lyr = child.children()
      lyr.sortItems(0,Qt.AscendingOrder)

But .children() appearantly returns a list(?)

The iface.legendInterface() group-options didn't help either...

Jason
  • 198
  • 8

1 Answers1

6

Sorting layers is a particularly painful task in PyQGIS, because of the lack of suitable methods in the QgsLayerTreeNode class. Based on your code, I managed to write a console script that seems to work (after multiple tests...).

Disclaimer #1: backup your project before testing this script.

Disclaimer #2: this script only sorts 1st-level groups (I didn't test it on subgroups).

Here we are:

root = QgsProject.instance().layerTreeRoot()

for child in root.children():
    if isinstance(child, QgsLayerTreeGroup):
        lyrList = [c.layer() for c in child.children()]
        lyrSortList = sorted(lyrList, key=lambda x: x.name()) # sorts layers based on name

        for idx, lyr in enumerate(lyrSortList):
            treeLyr = child.insertLayer(idx, lyr) # adds sorted layers to group

        child.removeChildren(len(lyrList),len(lyrList)) # removes previous layers

Note that the sorted layers will be visible. Use the setVisible() method to change that behavior.

ArMoraer
  • 5,649
  • 2
  • 26
  • 48