5

So I've read about the processing scripts you can do in QGIS 3. However, there seems to be no way of just modifying a layer directly and instead I have to have an output layer, which I do not want.

If you check at https://github.com/qgis/QGIS-Enhancement-Proposals/issues/134, they say that

it's best to have at least one out always defined to avoid fully black box algorithms if none is set. If a output isn't defined it will raise an exception.

The problem I have with that is because the module I am working on right now only adds fields and changes values in the attribute table. The output layer I would create would need to be deleted right after because there would be nothing in it.

All I want is the Input layer and make my changes within that layer, the output is a hindrance. If there is indeed no way to not have an output I would like to know if there's a way for the output to be just a log for example or something like that that way at least it could be of some use.

2
5

You should use QgsProcessingParameterVectorLayer as input in initAlgorithm method and use self.parameterAsVectorLayer to get the layer reference in processAlgorithm method. Then you can use methods and properties of QgsVectorLayer class.

This is a sample script which gets a vector layer you specified, adds/populates a field and returns the layer itself.

from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsField,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterVectorLayer)

class TestAlgorithm(QgsProcessingAlgorithm):
    INPUT = 'INPUT'

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterVectorLayer(self.INPUT, self.tr('Input layer')))

    def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)

        ### PROCESS ###
        input_layer.startEditing()
        input_layer.addAttribute(QgsField("Test_Field", 10, len=50)) # 10: Type String
        for feature in input_layer.getFeatures():
            feature["Test_Field"] = "TEST"
            input_layer.updateFeature(feature)
        input_layer.commitChanges()
        ###############

        return {"OUTPUT": input_layer.id()}

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return TestAlgorithm()

    def name(self):
        return 'test'

    def displayName(self):
        return self.tr('Test')

    def group(self):
        return self.tr('Example Scripts')

    def groupId(self):
        return 'example_scripts'

    def shortHelpString(self):
        return self.tr('')

I am not sure if this is the best approach.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.