2

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:

enter image description here

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:

enter image description here

1
  • 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
    – Kalak
    Commented Mar 22, 2023 at 9:39

1 Answer 1

5

I've written a script to access easily to layer(s) and group(s) in QGIS Layer Panel.

Here's the group part:

def G(group_path: str = None):
    """
    Return the group given in path
    If group_path is None, returns root
    """

    group = QgsProject.instance().layerTreeRoot()

    if group_path:
        groups =  group_path.strip("/").split('/')
        for g in groups:
            group = group.findGroup(g)
            if not group:
                raise Exception(f"Not found")

    return group


layer = QgsVectorLayer('None', "layer", "memory")

group = G('group B/group A')
group.addLayer(layer)

enter image description here

1
  • Thanks for the reply. This piece of code is useful. I wasn't aware of the possibility to find a group within a group but still, it's not exactly what I am looking for because the same problem will occur when I have a group with a sub-group that have the same names as another group with a sub-group. ie in the above example group B was renamed to group A. QGIS needs to provide a unique id for all groups just like it does for layers Commented Mar 22, 2023 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.