I have a list of raster layers that I want to do a calculation on each layer with QgsRasterCalculator. My code is:

lstLyr = self.readRasters()

    for layer in lstLyr:
        registry = QgsMapLayerRegistry.instance()
        lyr = registry.mapLayersByName(layer)
        namlyr = lyr[0].name()

        output = "/LorDataPlugin/Data/Temps/Normlized_%s.tif" % str(namlyr)

        fileName = layer
        fileInfo = QFileInfo(fileName)
        baseName = fileInfo.baseName()
        lyr2 = QgsRasterLayer(fileName, baseName)

        entries = []

        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = namlyr + '@1'
        ras1.raster = lyr2
        ras1.bandNumber = 1

        formula = ras1.ref + '/' + str(self.sumValue(lyr2))

        calc = QgsRasterCalculator(formula, output, 'GTiff', lyr2.extent(), lyr2.width(), lyr2.height(), entries)


But when run it without any error message, nothing happens. what is error in this code?

1 Answer 1


My guess is there's probably an issue with your formula. I would suggest to enclose the name of the layer in double quotation marks, this is useful especially when you have layer names which include more than one word separated by a 'space' (as the raster calculator will likely interpret this as being two different objects).

Try replacing your formula:

formula = ras1.ref + '/' + str(self.sumValue(lyr2))


formula = "\"" + ras1.ref + "\"" + ' / ' + str(self.sumValue(lyr2))
  • Hi @Joseph, I used your suggestion but not work. Sorry I think the problem relate to baseName = fileInfo.baseName() and lyr2 = QgsRasterLayer(fileName, baseName) because when I test inQMessageBox.Warning after this lines it shows the layer name instead of file path. I remember that my layers come from combobox Qt.
    – HMadadi
    Commented Aug 28, 2017 at 10:14
  • @nickan - Can you explain what your code is supposed to do please? I'm a little confused as it seems you're taking the first raster in the list and dividing this by all following rasters. Is that the case?
    – Joseph
    Commented Aug 29, 2017 at 9:10
  • Sorry for my delay response. I build a QGIS plugin that it get some raster file by Combo Box. Then I want to divide each raster file to sum value of all value raster of each raster layer.
    – HMadadi
    Commented Aug 30, 2017 at 17:38

Your Answer

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

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