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()
order = treeRoot.customLayerOrder()
treeRoot.setCustomLayerOrder( order )

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

Using QGIS modules on Android Studio

Updated October 29, 2017 17:22 PM