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
78.6k57 gold badges260 silver badges407 bronze badges
asked Dec 2, 2021 at 0:06
2
  • The objects found by findLayers() are QgsLayerTreeLayer, which have a layer() method to get the corresponding QgsVectorLayer. That's it. Commented 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. Commented 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()
answered Dec 2, 2021 at 1:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.