4

I am looking for a way of moving a layer to the top of the layer order once another layer is loaded. Using the following code extracted from this answer I get the error: AttributeError: 'QgsLayerTreeMapCanvasBridge' object has no attribute 'customLayerOrder'

    shapeindex = self.iface.mapCanvas().currentLayer()
    bridge = self.iface.QgslayerTreeCanvasBridge()
    order = bridge.customLayerOrder()
    order.inster(0, order.pop(order.index(shapeindex.id())))
    bridge.setCustomLayerOrder(order)

I looked into pyqgis3 documentation but it doesn't show more than the function name: QgsLayerTreeMapCanvasBridge

Thriskel
  • 355
  • 1
  • 14

1 Answers1

5

If you look at the documentation, you can see the changes in the API.

https://qgis.org/api/api_break.html#qgis_api_break_3_0_QgsLayerTreeMapCanvasBridge

Using your example you must use this

vlayer = iface.activeLayer()
root = QgsProject.instance().layerTreeRoot()
root.setHasCustomLayerOrder (True)
order = root.customLayerOrder()
order.insert(0, order.pop( order.index( vlayer ) ) ) # vlayer to the top
root.setCustomLayerOrder( order )

but this code change the order in which layers will be rendered on the canvas,it doesn't physically move.If you want move physically need something like this:

alayer = QgsProject.instance().mapLayersByName("trails")[0]

root = QgsProject.instance().layerTreeRoot()

# Move Layer
myalayer = root.findLayer(alayer.id())
myClone = myalayer.clone()
parent = myalayer.parent()
parent.insertChildNode(0, myClone)
parent.removeChildNode(myalayer)

or for automatic update

def rearrange( layers ):
    root = QgsProject.instance().layerTreeRoot()
    order = root.customLayerOrder()
    for layer in layers: # How many layers we need to move
        order.insert( 0, order.pop() ) # Last layer to first position
    root.setCustomLayerOrder( order )

QgsProject.instance().legendLayersAdded.connect( rearrange )

I hope it helps you

Fran Raga
  • 7,838
  • 3
  • 26
  • 47