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.
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)
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?
Answer
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)
No comments:
Post a Comment