0

I'd like to reorder the layers within ONE specific group of the TOC alphabetically by layer name, but without reordering the top level layers or the layers of other groups. @GérmanCarillo helped me to solve this (see link below).

I'm now struggling with removing old layers automatically (I just have some basic knowledge in R, but none in Python):

In the sample of Gérman Carillo the old layer structure is automatically removed, and only the layers in the intended order remain (see animation on Sorting layers by name in one specific group of QGIS layer tree). This is exactly the result I'd like to have but if I run the script in my QGIS (3.16), always both remain, one set of all layers in the origin order and another set in the new/intended order (see image below).

Does anybody have an idea what's going wrong here or know how to modify the script to delete the former layer set?

This is the current code:

from collections import OrderedDict

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("group1") # name of the to-be-sorted-group
reverse_order = False

LayerNamesEnumDict=lambda listCh:{listCh[q[0]].name()+str(q[0]):q[1]
                                   for q in enumerate(listCh)}
    
mLNED = LayerNamesEnumDict(group.children())
mLNEDkeys = OrderedDict(sorted(LayerNamesEnumDict(group.children()).items(), reverse=reverse_order)).keys()

mLNEDsorted = [mLNED[k].clone() for k in mLNEDkeys]
group.insertChildNodes(0,mLNEDsorted) 
for n in mLNED.values():
    group.removeChildNode(n)

This is the image of the result after running the script

enter image description here

3
  • I've been unable to reproduce your problem in both GNU/Linux and Windows, on QGIS 3.16.5. Any other info of your environment? Is there more than one group called 'group1'? Are you using always the same .qgz project or have you attempted to start a new project and see how it goes? Commented May 29, 2021 at 14:20
  • I'm using Win10, QGis 3.16.7 Desktop +++ No there isn't another 'group1' <-- The image shows the complete TOC after running the script, - there are no more layers or groups. Before running the script the TOC looks like the same, but of course without the sorted layers (blue marked). +++ Yes, I took the same qgz project. +++ I tried it also with one of the groups of my current Sentinel time series project. Each group contains about 200 GeoTiffs. Analogue result: Sorting worked perfect, but I had to remove the origin set (of 200 layers) manually.
    – jaysigg
    Commented Jun 2, 2021 at 14:33
  • Does anything change if you attempt to use the script with a new QGIS project? Commented Jun 2, 2021 at 14:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.