[Qgis-user] loadNamedStyle

Stephen Sacks ssacks456 at gmail.com
Mon Sep 13 07:33:27 PDT 2021


I'm writing a Python script to load a "qml" style file.  The following 
two lines work correctly:
    lyr1 = iface.activeLayer()
    lyr1.loadNamedStyle('xxx.qml')
but the following two lines cause an error message:
    lyr2 = instance.parameterAsSource(parameters, "INPUT", context)
    lyr2.loadNamedStyle('xxx.qml')
    AttributeError:  QgsProcessingFeatureSource: object has no attribute 
'loadNamedStyle'
     My problem is that
         lyr1 is  a  QgsVectorLayer  but  lyr2 is a 
QgsProcessingFeatureSource
So the issue comes down to how to load a named style file onto a 
QgsProcessingFeatureSource.   The complete code is below.   Thanks for 
any advice.   Steve
======================
from qgis import processing
from qgis.processing import alg
from qgis.core import QgsProject
from qgis.utils import iface

@alg(name='getMyStyle', label='load BigPicStyle on the active layer (alg)',
      group='examplescripts', group_label='Example scripts')
@alg.input(type=alg.SOURCE, name='INPUT', label='Input vector layer')
@alg.input(type=alg.STRING, name='theStyle', label='name of style file')
@alg.output(type=alg.STRING, name='OUTPUT', label='output lbl')

def getMyStyle(instance, parameters, context, feedback, inputs):
     """
     Asks for a style name and then loads that style.  By default,
        the layer acted on is the active layer, but a dropdown
        menu lets user choose another layer.
     """
     stylePath = 'C:/Promenade/GIS/data/styles/'
     whichFile = parameters.get('theStyle')
     #  note: lyr1 is QgsVectorLayer;  lyr2 is QgsProcessingFeatureSource
     lyr1 = iface.activeLayer()
     lyr2 = instance.parameterAsSource(parameters, "INPUT", context)
     lyr1.loadNamedStyle(stylePath + whichFile + '.qml')     #this works
     lyr1.triggerRepaint()
     #next line causes AttributeError:
     # 'QgsProcessingFeatureSource' object has no attribute 'loadNamedStyle'
     lyr2.loadNamedStyle(stylePath + whichFile + '.qml')
     lyr2.triggerRepaint()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20210913/66e8738b/attachment.html>


More information about the Qgis-user mailing list