2

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()

Taras
  • 32,823
  • 4
  • 66
  • 137
Wolverine
  • 39
  • 3
  • Maybe I solved it like this, tell me if it's correct:

    .... QgsProject.instance().addMapLayer(memory_layer, False) group_layer.addLayer(memory_layer) ....

    – Wolverine Dec 21 '23 at 15:07
  • 1
    Wolverine, yes- that is the correct approach. Add layer to project with 2nd argument set to False then add to group in the layer tree. – Ben W Dec 21 '23 at 23:58

1 Answers1

2

There are several things regarding your code:

  • work with isinstance() and children() of the QgsLayerTree node, instead of only if not group_layer::

    for child in root.children():
        if not isinstance(group_layer, QgsLayerTreeGroup):
            self.lg.info("Gruppo non trovato e aggiunto....")
            group_layer = root.addGroup(group_name)
        else:
            self.lg.info("Gruppo già nel Project QGis.")
    
  • to be sure one can also check the count of selected features with selectedFeatureCount():

    if self.layer_comuni.selectedFeatureCount() > 0:
    
  • selezioni = [] or selezioni = list() are maybe a bit shorter than selezioni :list = []

Apart from the above suggestions, you are doing a brilliant job with adding a layer to a group, exactly how @GermánCarrillo suggested in this thread: Adding layer to group using PyQGIS.

QgsProject.instance().addMapLayer(memory_layer, False) 
group_layer.addLayer(memory_layer)

References:

Taras
  • 32,823
  • 4
  • 66
  • 137