3

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...

5

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.

  • Yo, worked perfectly. Can't believe it finally can be done! And since I don't have subgroups - let's save this for another day. THANKS SO MUCH. – Jason Feb 18 '16 at 15:16
  • Good to hear that! I hope layer sorting will be easier in the next QGIS versions... – ArMoraer Feb 18 '16 at 15:19
  • So say we all... – Jason Feb 18 '16 at 15:21

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.