# 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'] 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?