0

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?

2

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)
0
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))
  • Feel free to expand your answer by explaining, what you did and how it works, in order to make it easier understandable. – Erik Feb 11 at 9:28

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.