[GIS] Load Named Style within a group on QGIS

groupingloadingpyqgisqgisstyle

I am trying to apply the style from .qml to a group of layers in QGIS. I have tried to incorporate LoadNamedStyle within jkall's code here:
https://github.com/jkall/qgis-processing-scripts/blob/master/set_transparency_for_group.py
I end up with this:

from qgis.core import *
def applystyle_group(name):
    root = QgsProject.instance().layerTreeRoot()
    point = root.findGroup(name) #Find Group AP
    for child in point.children():
        if isinstance(child, QgsLayerTreeLayer):
            if child.layer().type()==0:
                child.loadNamedStyle('*.qml')
applystyle_group("AK")

It gives me an error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:/OSGeo4W64/bin/applystyle_group.py", line 9, in <module>
     applystyle_group("AK")
  File "C:/OSGeo4W64/bin/applystyle_group.py", line 8, in applystyle_group
    child.loadNamedStyle('*.qml')
AttributeError: 'QgsLayerTreeLayer' object has no attribute 'loadNamedStyle'

Does QgsLayerTreeLayer have something similar to loadNamedStyle?

Best Answer

Change this line

child.loadNamedStyle('*.qml')

by:

child.layer().loadNamedStyle('/some/real/path/to/a/file.qml')

Your child object is of type QgsLayerTreeLayer, but you need to access layer() to get its correspondent QgsMapLayer, which has a loadNamedStyle() method.

Related Question