5

I am trying to add new layers into a specific group which I can get to work if I know the index, but how can I get Python to find the index of a group so it can load the new layer into the group wherever it is in the TOC?

qgis.utils.iface.legendInterface().moveLayer( layer, index )
10

[Updated to QGIS v3.x]

With the new layer list widget (aka legend, ToC or layer tree) added by Martin Dobias since QGIS v.2.4, you can follow this procedure from the QGIS Python console in order to add layers to a specific group (you won't need group indices anymore):

  1. Get the reference of the layer tree.

    root = QgsProject.instance().layerTreeRoot()

  2. Find the desired group.

    mygroup = root.findGroup("streets_group") # We assume the group exists

  3. Create the layer object.

    mylayer = QgsVectorLayer("/Path/to/your/data.shp", "my layer", "ogr")

  4. Load it to the QgsProject (set the second parameter to False since you want to define a custom position for the layer).

    QgsProject.instance().addMapLayer(mylayer, False)

  5. Add the layer to the desired group.

    mygroup.addLayer(mylayer)

Source: QGIS Layer Tree API, Part 1 and Part 2, by Martin Dobias

  • Does this still work when you load multiple layers from a directory as described in this post? I seem to get the same problem as described by the OP. – Joseph Mar 7 at 10:24
  • Just tested somethig like: for path in glob.glob("/geodata/*.shp"): mylayer = QgsVectorLayer(path, "my layer", "ogr") QgsProject.instance().addMapLayer(mylayer, False) mygroup.addLayer(mylayer) And it worked as expected. – Germán Carrillo Mar 7 at 11:40
  • Thanks for confirming, perhaps a bug in the version I am using :) – Joseph Mar 7 at 11:44
6

Recently I stumbled upon the same problem. It's not a recent question anymore, but for anyone else having the same question, here's the trick.

(TOC = table of contents)

toc = self.iface.legendInterface()
groups = toc.groups()

Now you have all groups listed in the groups variable. Based on the name of a group you can find the index, and move your new layer to the intended group based on the index:

groupIndex = groups.index(u'myGroup')
toc.moveLayer(newLayer, groupIndex)

This is more an extra, but in case the group myGroup would not exist, an error or exception will be thrown. You can handle that with try and except blocks.

# Do as what normally could/should be done...
try:
    groupIndex = groups.index(u'myGroup')
    toc.moveLayer(newLayer, groupIndex)
# Do this if the try didn't work...
except:
    groupIndex = toc.addGroup(u'myGroup', True)
    toc.moveLayer(newLayer, groupIndex)

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.