1

I'm trying to change the order of layers in qgis3 (python). But the code I can come up with only changes the order of layers in the list iface.mapCanvas().layers(), and not the displayed layer order in the lower left Layers Panel in the GUI.

My code below, e.g. swaps the orders of two arbitrary loaded layers. The print() statement shows that orders in layers() are indeed swapped with each run of the code.

lyr1 = iface.mapCanvas().layers()[0]
lyr2 = iface.mapCanvas().layers()[1]
treeRoot = QgsProject.instance().layerTreeRoot()
treeRoot.setHasCustomLayerOrder(True)
order = treeRoot.customLayerOrder()
order.append(order.pop(0))
treeRoot.setCustomLayerOrder( order )
iface.layerTreeCanvasBridge().setCanvasLayers()

print (iface.mapCanvas().layers()[0].name())
print (iface.mapCanvas().layers()[1].name())

I expected this to change the layer orders in QGIS GUI as well. However, the Layers Panel stays the same after running the scripts multiple times.

How can I synchronize the Layers Panel to reflect the order changes in the underlying layers()?

tinlyx
  • 11,057
  • 18
  • 71
  • 119
  • As far as I understand, you're setting the layer order in Layer Order Panel (see https://qgis.org/api/2.14/classQgsLayerTreeMapCanvasBridge.html#aa1da33b746370800346232bd89dba1e4) and not in the Layers Panel. From the docs, "This is useful in advanced cases where the grouping in layer tree should be independent from the actual order in the canvas." See this question for more context: https://gis.stackexchange.com/questions/229587/how-to-move-layers-in-the-layer-order-panel-using-pyqgis/229646#229646 – Germán Carrillo Jan 15 '18 at 04:03
  • @GermánCarrillo Thanks. Do you know how to change the layer order in non-"advanced" cases:) I searched quite a bit and couldn't find it. – tinlyx Jan 15 '18 at 04:22
  • Did you see this already? https://gis.stackexchange.com/questions/134284/moving-layers-in-qgis-table-of-contents-via-pyqgis/134305#134305 – Germán Carrillo Jan 16 '18 at 02:03

0 Answers0