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()?

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.