[GIS] Programmatically grouping multiple layers into separate groups using QGIS

group-layerpyqgistable of contents

I'm trying to group a large number of layers together based on a common portion of name string. They are a mix of polygons and points. I would like to create individual groups by using part of the layer's name. Anyone have any ideas? I was looking to build a plugin but I am unable to (due to my coding abilities).

I attached a picture to show what I'm looking for as the end result. I have projects with a large amount of information that needs to be grouped.

enter image description here

Best Answer

You can do it in three steps: Get group names, create groups, and move layers.

For testing purposes, I've replicated your sample scenario:

enter image description here

Run the following code snippet in your QGIS Python console:

# 1. Get group names and list of layer ids
root = QgsProject.instance().layerTreeRoot()
dictGroups={}
for layer in root.findLayers():
  if QgsLayerTree.isLayer(layer):
    prefix="Site "+layer.layerName().split("_")[0] # Adjust this to fit your needs
    if not prefix in dictGroups:
      dictGroups[prefix]=[]
    dictGroups[prefix].append(layer.layerId())

# 2. Create groups
for key in dictGroups:
  root.addGroup(key)

# 3. Move layers
for key in dictGroups:
  parent = root.findGroup(key)
  for id in dictGroups[key]:
    layer = root.findLayer(id)
    clone = layer.clone()
    parent.insertChildNode(0, clone)
    root.removeChildNode(layer)

You should get something like this:

enter image description here