PyQGIS – Retrieving Vector Layer from Layers within Group

pyqgisqgis-3qgslayertreeqgsvectorlayer

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?

Best Answer

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