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:
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.