PyQGIS – Resolving Symbology Loss When Adding the Same Layer Twice with Different Names

geopackagepyqgis

I’m trying to insert the same layer from a GPKG several times to the same QGIS project. I’d like to give it different names first as well as symbology and filters afterwards.

The code below works for adding the layer once. So when I insert the layer with Name1 (Layer1_Name1) it appears normally.

But when I add the same layer with Name2 (Layer1_Name2) the first added layer with “Name1” gets some kind of deactivated and loses its symbology. Also the menu looks very different. See the screenshots:

enter image description here
menu of "Layer1_Name1"

How can I add the same layer several times to a precise group correctly?

(What is happening here? To what kind of layer does the Name1-layer get transformed?)

lyr=QgsVectorLayer('C:\Testfolder\test.gpkg|layername=Layer1','Layer1_Name1', 'ogr')
root = QgsProject.instance().layerTreeRoot()
targetgroup = root.findGroup('sub_group')
group = targetgroup.insertLayer(0,lyr)

lyr=QgsVectorLayer('C:\Testfolder\test.gpkg|layername=Layer1','Layer1_Name2', 'ogr')
group = targetgroup.insertLayer(0,lyr)

I'm using QGIS 3.16.2

Edit: I just realised that the symbology disappears as well if I drag and drop the layer to another group.

If I manually duplicate the layer and move the duplicate, the symbology of both layers stays the same.

If I manually duplicate the layer and add a new one using python, the duplicate stays the same. It does not matter if I add the same layer with another name or the same.

So I tried to use the layer.clone() command. But this doesn’t work. I think there must be something wrong with the .insertChildNode() command, which I have to use after the .clone() to insert the clone at the correct position.

Best Answer

You will need to add layers with QgsProject.instance().addMapLayer() to correctly make QGIS aware of newly added layers. Set the addToLegend parameter to False if you want to specify the position in the layer tree (e.g. by using insertLayer)

root = QgsProject.instance().layerTreeRoot()
targetgroup = root.findGroup('sub_group')

lyr=QgsVectorLayer('D:\Downloads\example.gpkg|layername=line1','Layer1_Name1', 'ogr')
QgsProject.instance().addMapLayer(lyr, False) # this adds a new layer to the map layer registry
group = targetgroup.insertLayer(0,lyr) # this is only "visual" (position of where you want the layer)

lyr=QgsVectorLayer('D:\Downloads\example.gpkg|layername=line1','Layer1_Name2', 'ogr')
QgsProject.instance().addMapLayer(lyr, False)
group = targetgroup.insertLayer(0,lyr)

qgis

Related Question