I'm writing a plugin for QGIS and given a layer (self.layer_comuni) from this I extrapolate an indeterminate number of layers depending on the correspondence of the values of the mercato_comuni list with the "COMUNI" feature of the layer.
However, I cannot insert the layers obtained into a group, i.e. if I use group_layer.addLayer(memory_layer) I see them in the legend but not in the canvas, instead if I add them with QgsProject.instance().addMapLayer(memory_layer) I see them in the canvas but in the legend outside the group.
How can I get this to work?
def checkAndBuilderGiurisdizione(self, lista_comuni :list):
# crea il gruppo layer GIURISDIONE
group_name = "GIURISDIZIONE"
# cerca nella root se è già presente il gruppo
self.lg.info(f"Ricerca del gruppo {group_name} nella root di QGis....")
root = QgsProject.instance().layerTreeRoot()
group_layer = root.findGroup(group_name)
# se non lo è lo aggiunge e diventa attivo
if not group_layer:
self.lg.info("Gruppo non trovato e aggiunto....")
group_layer = root.addGroup(group_name)
else:
self.lg.info("Gruppo già nel Project QGis.")
selezioni :list = []
for comune in lista_comuni:
print(f"COMUNE : {comune}")
self.layer_comuni.selectByExpression(f"\"COMUNE\"='{comune}'", QgsVectorLayer.SetSelection)
selezioni.append(self.layer_comuni.selectedFeatures())
memory_layer = self.layer_comuni.materialize(QgsFeatureRequest().setFilterFids(self.layer_comuni.selectedFeatureIds()))
memory_layer.setName(f"{comune}")
#QgsProject.instance().addMapLayer(memory_layer, False)
group_layer.addLayer(memory_layer)
for selezione in selezioni:
for feature in selezione:
print(f"FEATURE COMUNE: {feature['COMUNE']}")
print(f"FEATURE AREA: {feature['Shape_Area']}")
iface.mapCanvas().refresh()
.... QgsProject.instance().addMapLayer(memory_layer, False) group_layer.addLayer(memory_layer) ....
– Wolverine Dec 21 '23 at 15:07Falsethen add to group in the layer tree. – Ben W Dec 21 '23 at 23:58