TransWikia.com

QGIS 3.16 Python script: processAlgorithm return empty layer

Geographic Information Systems Asked by Lalikinelo on July 31, 2021

The script process well except the returned output. I want that the script displays the "output_layer" at the end of my script as a temporary layer in my QGIS project.
I understand that the output have to be a sink type.

Following this tutorial: http://www.qgistutorials.com/en/docs/3/processing_python_scripts.html, I try to add the features of the output_layer in sink at the end of the script.

def initAlgorithm(self, config=None):
     
    self.addParameter(QgsProcessingParameterVectorLayer(self.INPUT_vector,self.tr( 
    'couche parcelle'), 
    types=[QgsProcessing.TypeVectorPolygon],
    defaultValue=None)
    )
    
    self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT_raster,self.tr(
    'raster classification'),
    defaultValue=None)
    )

    self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Output layer'), type=QgsProcessing.TypeVectorPolygon, createByDefault=True, defaultValue=None))
    

    
def processAlgorithm(self, parameters, context, feedback):       
    
    source = self.parameterAsSource(
        parameters,
        self.INPUT_vector,
        context
    )        


    (sink, dest_id) = self.parameterAsSink(
        parameters,
        self.OUTPUT,
        context,
        source.fields(),
        source.wkbType(),
        source.sourceCrs()
    )
    

    [...]
    

    # At the end of the script: Read output_layer and create output sink

    for f in output_layer['OUTPUT'].getFeatures():
        sink.addFeature(f, QgsFeatureSink.FastInsert)
        feedback.pushInfo('feature: {}'.format(f.fields().names()))
    
    
    return {self.OUTPUT: dest_id}

The displayed output layer contains the input layer fields instead of the output_layer fields. feedback.pushInfo displays correct info, "output_layer" is OK.

What is the correct code to have "output_layer" correctly returned and displayed at the end of the script?

2 Answers

I finaly find the solution:

The problem comes from the sink construction. line:

(sink, dest_id) = self.parameterAsSink(...)

I changed the source.fields() to output_layer['OUTPUT'].fields()

source.fields() was limiting the number of fields with the number of fields of the input layer.

Correct answer by Lalikinelo on July 31, 2021

First, you have to add the following method to your processing algorithm class to be able to add temporary layers to the project.

def flags(self):
    return super().flags() | QgsProcessingAlgorithm.FlagNoThreading

Then use this anywhere before return:

QgsProject.instance().addMapLayer(output_layer['OUTPUT'])

Answered by Kadir Şahbaz on July 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP