There are several similar questions around, like Sort layers in QGIS table of contents or Order layer in QGIS with PyQgis, but I can't get it to work. Here is what I do:

# image and shapefile are already defined
canvas = iface.mapCanvas()
li = iface.legendInterface()
lakes = [l for l in li.layers() if l.name() == 'lakes'][0]
raster = QgsRasterLayer(image, QFileInfo(image).baseName())

# set "lakes" layer on top:
for l in li.layers():
    if l.name() == lakes.name():
        li.moveLayer(l, 0)

The condition from "if" is fulfilled (I checked it several times using some print commands), but the "lakes" layer won't move to the top. Actually, nothing happens at all. Am I using the wrong function to set the layer order?

According to QGIS Layer Tree API (Part 2), I tried this

root = QgsProject.instance().layerTreeRoot()
for ch in root.children():
    if ch.layerName() == lakes.name():
        root.insertChildNode(0, ch)

which does the job for me. But why does moveLayer not do what it is supposed to do?

2 Answers 2


The QgsLegendInterface::moveLayer() method is used to move layers to a group index.

So if you create a new group and use your code, the layer should move inside this group. But if no groups are present, your layer will not move.

  • 1
    I see. Was not obvious to me, so thanks for the clarification.
    – s6hebern
    Commented Nov 23, 2017 at 10:55
  • @s6hebern - Most welcome! It was not so obvious to me either until I checked the API and it mentioned the int value being an index for groups and not layers :)
    – Joseph
    Commented Nov 23, 2017 at 10:57

You can change the code as follows:

root = QgsProject.instance().layerTreeRoot()
for ch in root.children():
    if ch.name() == lakes.name():
        _ch = ch.clone()
        root.insertChildNode(0, _ch)

QGIS Layer Tree API (Part 2) says "moving a node is done in three steps"

  1. Clone the existing layer,
  2. Insert the cloned layer to layer tree,
  3. Remove the original layer.
  • cloning is a common way to get the task done. When I used clone method, I was told to try and do it another way. Any ideas, or can you provide some reason why clone is the correct way? It seems to me that there is a lot of overhead while cloning and there might be a better way. Commented Apr 24, 2019 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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