How to synchronize layer orders in "layerTreeRoot().customLayerOrder()" and qgis3 Layers Panels

by tinlyx   Last Updated January 14, 2018 09:22 AM

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

My code below, e.g. swaps the orders of two arbitrary loaded layers. The print() statement shows that layer orders 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. However, the Layers Panel stays the same after running the scripts.

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

Tags : pyqgis qgis-3.0


Related Questions



Toggle Editing Add Feature

Updated September 04, 2018 13:22 PM

Qdialog control events not working for own ui design

Updated September 20, 2018 09:22 AM