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:
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)
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.