[GIS] Set layer order in QGIS with PyQGIS

layerspyqgistable of contents

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()
iface.addVectorLayer(shapefile)
iface.addRasterLayer(image)
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)
        root.removeChildNode(ch)

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

Best Answer

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.

Related Question