5

It's not difficult to get a list of layers within a group in the Layers panel of a QGIS 3.x project:

root = QgsProject.instance().layerTreeRoot()
groupName = "GROUP_name"
group = root.findGroup(groupName)
layers = group.findLayers() # gets all <QgsLayerTreeLayer> objects in the group

Once I have the layer objects, I'm trying to apply symbology from a .qml file. This is where I run into problems - I think you need a QgsVectorLayer object in order to apply the symbology via the load NamedStyle() method as below:

vLayer = QgsProject.instance().mapLayersByName("name of layer here")[0]
vLayer.loadNamedStyle(thisQMLpath)
vLayer.triggerRepaint()

The gap I'm trying to fill is how to get from a list of <QgsLayerTreeLayer> objects to individual QgsVectorLayer objects. Tried something like this using the .mapLayersByName() method:

layers = group.findLayers() # a list of <QgsLayerTreeLayer> objects in the group
for x in layers:
     vLayer = QgsProject.instance().mapLayersByName(x)[0]

but x is not a layer name string, so it doesn't work.

Any ideas?

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
grego
  • 1,043
  • 7
  • 18
  • The objects found by findLayers() are QgsLayerTreeLayer, which have a layer() method to get the corresponding QgsVectorLayer. That's it. – Germán Carrillo Dec 02 '21 at 00:13
  • Have a look at this answer, specifically the 'Layers in TOC' section: https://gis.stackexchange.com/questions/26257/iterating-over-map-layers-using-python-in-qgis/416933#416933 Let us know if that solves your question. – Germán Carrillo Dec 02 '21 at 00:27

1 Answers1

5

QgsLayerTreeLayer has a layer() method which returns QgsMapLayer associated with the node as @GermánCarrillo mentioned.

Use this script:

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("GROUP_NAME")

for layer in group.findLayers(): name = layer.layer().name() # <- vLayer = QgsProject.instance().mapLayersByName(name)[0] vLayer.loadNamedStyle("path/to/QML") vLayer.triggerRepaint()

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389