4

Hi this may be more of a python question rather than qgis processing script question. I've managed to successfully get the output that I want from my processing script, but I wish to take one step further and style it automatically with a saved qml file.

The code below doesn't work because the return ends my script. How should I go about doing this?

return {self.OUTPUT: dest_id}
iface.activeLayer().loadNamedStyle('Buffer.qml')
iface.activeLayer().triggerRepaint()
TomazicM
  • 25,601
  • 22
  • 29
  • 39
sjp_1989
  • 569
  • 3
  • 11
  • Are you trying to set the style after the processing tool (from Python) or are you trying to set the style from within the processing tool itself? – etrimaille Aug 31 '19 at 09:48

1 Answers1

1

You would need to create a subclass of QgsProcessingLayerPostProcessorInterface and apply the style in it's postProcessLayer method

First define the post processor class and create an an instance as follows

class LayerStyler(QgsProcessingLayerPostProcessorInterface):
    def postProcessLayer (self, layer, context, feedback):
        if layer.isValid():
            layer.loadNamedStyle('my_style.qml')

my_styler = LayerStyler()

Then set the post processor in processAlgorithm

def processAlgorithm():
    ...
if context.willLoadLayerOnCompletion(dest_id):
    context.layerToLoadOnCompletionDetails(dest_id).setPostProcessor(my_styler)

return {self.OUTPUT: dest_id}

Prithvi
  • 93
  • 5