7

I have a QgsProcessingLayerPostProcessorInterface class as shown below.

class LayerPostProcessor(QgsProcessingLayerPostProcessorInterface):
    instance = None
    name = ""
    color1 = tuple()
    color2 = tuple()

    def postProcessLayer(self, layer, context, feedback):
        feedback.pushInfo("here")
        if layer.isValid():
            layer.setName(self.name)

            prov = layer.dataProvider()
            stats = prov.bandStatistics(1, QgsRasterBandStats.All, layer.extent(), 0)
            min = stats.minimumValue
            max = stats.maximumValue
            renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1)
            color_ramp = QgsGradientColorRamp(
                QColor(*self.color1), QColor(*self.color2)
            )
            renderer.setClassificationMin(min)
            renderer.setClassificationMax(max)
            renderer.createShader(color_ramp)
            layer.setRenderer(renderer)

    # Hack to work around sip bug!
    @staticmethod
    def create(name, color1, color2) -> "LayerPostProcessor":
        LayerPostProcessor.instance = LayerPostProcessor()
        LayerPostProcessor.name = name
        LayerPostProcessor.color1 = color1
        LayerPostProcessor.color2 = color2
        return LayerPostProcessor.instance

In my main code, I loop over multiple layers and want to style them using the above class, but when I do that only the last layer is styled. I tried deepcopy and subclass, nothing worked. Can't seem to figure out what is going on.

I changed the class and tried initiating it in a regular way using the init method. That didn't work at all, even the last layer didn't get post-processed.


    for display_name, layer in layers.items():
        layer_details = context.LayerDetails(
            display_name, context.project(), display_name
        )
        context.addLayerToLoadOnCompletion(
            layer,
            layer_details,
        )
        if context.willLoadLayerOnCompletion(layer):
            context.layerToLoadOnCompletionDetails(layer).setPostProcessor(
                LayerPostProcessor.create(display_name, (255, 0, 0), (0, 0, 255))
            )
1
  • Have you tried applying the style at the end of the processAlgorithm method (if you are running this within a Processing Algorithm)? You can style multiple outputs without the need for a PostProcessor
    – Andre Geo
    Commented Dec 22, 2023 at 11:44

0

Your Answer

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

Browse other questions tagged or ask your own question.