How to move layers in the Layer Order Panel using PyQGIS?
You can set layer order in the Layer Order Panel
"manually" using QgsLayerTreeCanvasBridge.setCustomLayerOrder()
method, which receives an ordered list of layer ids. For instance (assuming you just loaded vlayer
):
bridge = iface.layerTreeCanvasBridge()
order = bridge.customLayerOrder()
order.insert( 0, order.pop( order.index( vlayer.id() ) ) ) # vlayer to the top
bridge.setCustomLayerOrder( order )
To automatically move newly added layers to the top of Layer Order Panel
, you could use the legendLayersAdded
SIGNAL (this signal is appropriate because it's emitted after the Layer Order Panel
gets the new layer) from QgsMapLayerRegistry
and reorder layers in this way:
def rearrange( layers ):
order = iface.layerTreeCanvasBridge().customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
iface.layerTreeCanvasBridge().setCustomLayerOrder( order )
QgsMapLayerRegistry.instance().legendLayersAdded.connect( rearrange )
NOTE: Since you're loading your vlayer
calling QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
, that False
parameter prevents the legendLayersAdded
SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer).
Hi sorry I can't comment, but the method "bridge.customLayerOrder()" doesn't exist in QGis 3.x
I've found maybe a substitute command:
bridge = iface.layerTreeCanvasBridge()
bridge.rootGroup().customLayerOrder()
From https://qgis.org/api/classQgsLayerTree.html#aab7a55f2e61f0ff1dbea6ceb89e8b366:
The order in which layers will be rendered on the canvas. Will only be used if the property hasCustomLayerOrder is true. If you need the current layer order that is active, prefer using layerOrder().
Hope to be useful to others.
Riccardo