I am having trouble when loading some layers in QGIS. I want to place them in specific groups and sub-groups but a problem occurs when multiple groups and sub-groups have the same name. The only way I can retrieve a group or a sub-group is by using its name:
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('group_name')
group.insertLayer(0, layer)
Is there a way to retrieve a group or a sub-group using a unique identifier? If you create these groups in QGIS:
and execute the following code in the python console you will see that QGIS always places the layer under the first group it finds to have that name.
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('group A')
uri = "point?crs=epsg:4326&field=id:integer"
layer = QgsVectorLayer(uri, "Scratch point layer", "memory")
QgsProject.instance().addMapLayer(layer, False)
group.insertLayer(0, layer)
but instead, I want to place it here:
findGroup(name)
returns the first found with the name so you can't expect it to be placed in a specific group if you have multiple group named the same, at least the way you tried