Tuesday, 15 September 2015

Adding layer to group in layers panel using PyQGIS?


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?




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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...