PyQGIS – How to Move Layers in Layer Order Panel

pyqgisqgistable of contents

Related to the following question but looking for a PyQGIS method:

QGIS Layer Order Panel – add layers at top of layer order


The following is a simple setup containing a group with three layers.

Simple setup

The code I use adds a new layer at the end of this group:

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')

vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))  

New layer added at end of group

In the Layer Order Panel, the newly added layer is at the end.

Layer Order Panel


Is it possible to move this to the top without moving the layer in the Layers Panel?

Best Answer

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

Related Question