1

I am trying to execute an algorithm and load it in the layer tree when it is done. After looking online I saw that I could use processing.runAndLoadResults() to load my result when the algorithm is done but it does not load it in the layer tree but it is accessible as a layer when i'm trying to execute another algorithm. I even tried to use QgsProject.instance().addMapLayer() but no luck there either.

Here is my script:

from PyQt5.QtCore import (QCoreApplication,
                          QFileInfo)
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterString,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterRasterLayer,
                       QgsProcessingParameterRasterDestination,
                       QgsMessageLog,
                       QgsVectorLayer,
                       QgsRasterLayer,
                       QgsProject)
import processing, os

class foo(QgsProcessingAlgorithm):

    LAYER1 = 'LAYER1'
    LAYER2 = 'LAYER2'
    OUTPUTDIR = 'OUTPUTDIR'
    DEBUGMODE = 'DEBUGMODE'

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

    def createInstance(self):
        return foo()

    def name(self):
        return 'foo'

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

    def group(self):
        return self.tr('Script')

    def groupId(self):
        return 'Script'

    def initAlgorithm(self, config=None):

        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.LAYER1,
                self.tr('Raster Layer 1.')
            )
        )

        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.LAYER2,
                self.tr('Raster Layer 2.')
            )
        )

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.DEBUGMODE,
                self.tr('Ajoute la couche resultant de chaque opération dans QGIS.')
            )
        )

        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.OUTPUTDIR,
                self.tr('Output Directory')
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        layer1 = self.parameterAsRasterLayer(parameters, self.LAYER1, context)
        layer2 = self.parameterAsRasterLayer(parameters, self.LAYER2, context)
        outputDir = self.parameterAsString(parameters, self.OUTPUTDIR, context)
        self.DEBUGMODE = self.parameterAsBool(parameters, self.DEBUGMODE, context)
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        ext = "%f,%f,%f,%f" %(LAYER1.extent().xMinimum(), LAYER1.extent().xMaximum(), LAYER1.extent().yMinimum(), LAYER1.extent().yMaximum())
        newDir = outputDir + "/test"
        os.system('mkdir "' + newDir + '"')

        params = {'GRIDS': layer1, 'XGRIDS': [layer2], 'FORMULA': 'a-b', 'RESAMPLING': 0, 'USE_NODATA': False, 'TYPE': 7, 'RESULT': newDir + '/Calculated.sdat'}
        result = self.RunAlg('saga:rastercalculator', params, feedback)


        #feedback.pushDebugInfo(self.OUTPUTDIR)
        output = result["RESULT"]

        return {self.OUTPUT: output}

    def RunAlg(self, algName, params, feedback):
        if self.DEBUGMODE:
            feedback.pushDebugInfo("debug")
            result = processing.runAndLoadResults(algName, params, feedback=feedback)
        else:
            result = processing.run(algName, params, feedback=feedback)

        return result

    def StringToRaster(self, raster):
        fileInfo = QFileInfo(raster)
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        if(".shp" in path):
            layer = QgsVectorLayer(path, baseName, "ogr")
        else:
            layer = QgsRasterLayer(path, baseName)

        if layer.isValid() is True:
            QgsMessageLog.logMessage("Layer " + baseName  + " was loaded successfully!", 'MyPlugin')
            return layer

        else:
            QgsMessageLog.logMessage("Unable to read basename and file path - Your string is probably invalid", 'MyPlugin', Qgis.Info) 
  • That's fixed in 3.4.6 – ndawson Mar 21 at 21:31
  • actualy it does'nt even work in 3.6 :/ same issue – Jean-Simon Tremblay Mar 22 at 13:10
  • Yes, you need 3.6.1 – ndawson Mar 23 at 1:52

Your Answer

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

Browse other questions tagged or ask your own question.