Skip to content

Instantly share code, notes, and snippets.

@Korto19
Last active July 22, 2022 09:02
Show Gist options
  • Save Korto19/de7120d35efcda209d789cf3c1f445cc to your computer and use it in GitHub Desktop.
Save Korto19/de7120d35efcda209d789cf3c1f445cc to your computer and use it in GitHub Desktop.
Reorder layer in selected group
# Algorithm for QGIS console
# first select group
# repeat to reverse order
from collections import OrderedDict
root = QgsProject.instance().layerTreeRoot()
group_sel = iface.layerTreeView().selectedNodes()
group = root.findGroup(group_sel[0].name())
if root.findGroup(group_sel[0].name()):
if 'rev' not in locals():
rev = True
sort_order = 'descending'
else:
if rev == True :
rev = False
sort_order = 'ascending'
else:
rev = True
sort_order = 'descending'
LyrInGroup = lambda listCh:{listCh[lyr[0]].name()+str(lyr[0]):lyr[1] for lyr in enumerate(listCh)}
lyr_names = LyrInGroup(group.children())
lyr_keys = OrderedDict(sorted(LyrInGroup(group.children()).items(), reverse=rev)).keys()
lyr_sorted = [lyr_names[k].clone() for k in lyr_keys]
group.insertChildNodes(0,lyr_sorted)
for n in lyr_names.values():
group.removeChildNode(n)
print('group ordered ' + sort_order.upper())
else:
print('NOT A GROUP')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment