3

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?

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
s6hebern
  • 1,236
  • 10
  • 19

2 Answers2

3

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.

Joseph
  • 75,746
  • 7
  • 171
  • 282
  • 1
    I see. Was not obvious to me, so thanks for the clarification. – s6hebern Nov 23 '17 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 Nov 23 '17 at 10:57
3

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)
        root.removeChildNode(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.
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
  • 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. – Ely Fialkoff Apr 24 '19 at 13:23