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

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


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


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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.