4

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?

2
  • The objects found by findLayers() are QgsLayerTreeLayer, which have a layer() method to get the corresponding QgsVectorLayer. That's it. Dec 2, 2021 at 0:13
  • Have a look at this answer, specifically the 'Layers in TOC' section: gis.stackexchange.com/questions/26257/… Let us know if that solves your question. Dec 2, 2021 at 0:27

1 Answer 1

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()

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.