1

I''ve created a function to add layers to a QGIS project:

def add_layer_to_project(layer, group_lst=None, visible=True):
    """
    group name has to be list relative to root of project
    root
        group
            subgroup
                subsubgroup for example
    """
    try:
        root = QgsProject.instance().layerTreeRoot()
        # If group is specified, create it if it doesn't exist yet
        if group_lst:
            QgsProject.instance().addMapLayer(layer, False)
            # Last item in list represent group to add layer to
            group = ensure_group(group_lst, root)
            group.addLayer(layer)
        else:
            QgsProject.instance().addMapLayer(layer, visible)
    except Exception as e:
        raise e from None

I call the function like this:

add_layer_to_project(layer)

Layer can be raster or vector layer and is created elsewhere.

The intent is to add a layer to either a group in my project or to the root of it. However, if I have a group selected and I try to add layers to the root (see else clause), they get added to that group instead. I haven't tried what happens if I try to create a group but I imagine it somehow sees whatever is selected as the root? I was hoping someone could tell my how to make sure that root is actually the root if the layer tree.

(P.S. I have found a lot of answers that describe how to add layers to a group, but I couldn't find this)

P.S. The ensure_group function just creates groups and subgroups if needed, I didn't think I should paste the code since the problem occurs when it isn't called.

3

You should use the same logic in your else clause as you do in your first condition.

E.g. In your else clause you should add the layer to the project without adding it to the legend:

QgsProject.instance().addMapLayer(layer, False)

Then add it to the layer tree root:

root.addLayer(layer)

Note that addLayer() appends the layer node to the end of a group. To have greater control over the position of added layers you can use the insertLayer() method, passing the index of the position at which the layer node should be added as the first argument. For example, to insert a layer at the top of the Table Of Contents use:

root.insertLayer(0, layer)

Or at the top of a group:

group.insertLayer(0, layer)
1
  • Thank you, for the explanation too! – Laure Ravier Feb 6 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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