7

I am trying to add a group to the layer panel, then place a vector layer (vectorLayer) into this group from a python script. The code I am using is:

groupName="test group"
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup(groupName)

group.insertChildNode(-1, QgsLayerTreeLayer(vectorLayer))
QgsMapLayerRegistry.instance().addMapLayer(vectorLayer,True)

My issue is that this code always adds two copies of the vector layer. One of which will be in the group, the other is outside the group.

enter image description here

However, when I change the code to the following with the intent of not adding a second layer, the layer inside the group becomes '(?)'.

groupName="test group"
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup(groupName)

group.insertChildNode(-1, QgsLayerTreeLayer(vectorLayer))
# QgsMapLayerRegistry.instance().addMapLayer(vectorLayer,True)

enter image description here

Does this mean the layer inside the group is just a pointer to the layer outside the group?

How do I add a layer to a group without the duplicate layer?

0

3 Answers 3

18

Use addMapLayer(layer,False), which will add a layer without showing it

memlay = QgsVectorLayer("Point","myLayer", "memory")
QgsProject.instance().addMapLayer(memlay, False)    #False is the key
sgroup.addLayer(memlay) 

Then you can simply add it to an existing group without cloning etc.

8

You have to make a clone of the layer and then move it and remove the original layer, try:

groupName="test group"
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup(groupName)
vlayer = QgsVectorLayer("C:/Temp/myShp.shp", "shpName","ogr")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
root = QgsProject.instance().layerTreeRoot()
layer = root.findLayer(vlayer.id())
clone = layer.clone()
group.insertChildNode(0, clone)
root.removeChildNode(layer)
2
  • 5
    Important note for QGIS 3.x users: QgsMapLaye Registry is extinct! Use QgsProject.instance().addMapLayer(vlayer) instead.
    – grego
    Commented Jul 23, 2020 at 16:49
  • You probably want to use layer.parent().removeChildNode(layer) instead on the last line, then it will also work if a group is selected while the new layer is inserted Commented Oct 18, 2023 at 15:52
3
groupName ="test group"
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup(groupName)
vlayer = QgsVectorLayer("C:/Temp/myShp.shp", "shpName","ogr")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
group.insertChildNode(1, QgsLayerTreeLayer(vlayer))
1
  • Feel free to expand your answer by explaining, what you did and how it works, in order to make it easier understandable.
    – Erik
    Commented Feb 11, 2019 at 9:28

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