I want to clone my generated memory layer and apply different filters and symbology. The clone is visible in the layer tree, but doesn't show up in the canvas. What am I doing wrong?
uri = f'point?crs=EPSG:25832&field=id:integer&index=yes'
l_out = QgsVectorLayer(uri, 'new layer', 'memory')
x, y = 369000, 5616000
with edit(l_out):
for i in range(10):
f = QgsFeature(l_out.fields())
g = QgsGeometry(QgsPoint(x, y))
f.setGeometry(g)
f.setAttributes([i])
l_out.addFeature(f)
x += 50
y += 50
project = QgsProject.instance()
project.addMapLayer(l_out)
tree = project.layerTreeRoot()
group0 = tree.insertGroup(0, 'level 0')
group1 = group0.addGroup('level 1')
lcopy = project.addMapLayer(l_out.clone(), False)
nodecopy = group1.insertLayer(-1, lcopy)
Best Answer
There are several suggestions regarding your code:
adding the same layer
l_out
one more time to the project, even with theaddToLegend = False
does not make much sense to me. In the documentation for theaddMapLayer()
method, it says whatReturns
it possesses:However, the type of the
lcopy
-variable is theQgsVectorLayer
. On the another side, theinsertLayer()
method works withQgsMapLayer
andQgsVectorLayer
.no need to create the
nodecopy
-object, simply proceed with:application of these methods i.e.
isValid()
andhasFeatures()
can be useful to check if yourQgsVectorLayer
is solid:I can also suggest several workarounds:
using the
findLayer()
method of theQgsLayerTreeGroup
class:proceeding without cloning:
applying the
materialize()
method: