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).