1

I have a QgsRasterLayer and want to process it in a processing script with qgis:rastercalculator. How can I customize the name under which the layer is referenced in the expression? It seems that QGIS uses the file's basename but I would like to explicitly specify it myself.

This is working:

raster_layer = QgsRasterLayer("//tmp/my_file.tif")

parameters = {
    'EXPRESSION': "my_file@1 * 2",
    'LAYERS': [raster_layer],
    'OUTPUT': 'TEMPORARY_OUTPUT',
}

processing.runAndLoadResults("qgis:rastercalculator", parameters)

But instead of having to hard-code the file's basename in the expression (my_file) I would like to use an arbitrary identifier, e.g. raster_a. How can I do this?

I already tried these possible options but neither of them had an effect on the reference usable in the expression:

  • Setting raster_layer = QgsRasterLayer(..., baseName="test") on instantiation
  • raster_layer.setName("test")
  • raster_layer.setShortName("test")
  • raster_layer.setTitle("test")
1

1 Answer 1

1

I'm not sure that there is a canonical solution to this issue, but here are a couple of workarounds to avoid hardcoding the file name into the raster calculator expression.

Firstly, I found that if you add the layer to the project instance (which you can do without adding it to the table of contents by setting the addToLegend argument to False), then remove it after running the calculation, then the layer name passed to the QgsRasterLayer constructor is recognized.

raster_layer = QgsRasterLayer("//tmp/my_file.tif", 'Test_layer')

QgsProject.instance().addMapLayer(raster_layer, False)

parameters = {
    'EXPRESSION': "Test_layer@1 * 2",
    'LAYERS': [raster_layer],
    'OUTPUT': 'TEMPORARY_OUTPUT',
}

processing.runAndLoadResults("qgis:rastercalculator", parameters)

QgsProject.instance().removeMapLayer(raster_layer)

Alternatively, if you don't like this approach you could always just retrieve the file name from the file path string and insert it dynamically into the expression string. The following should work:

from pathlib import Path

file_path = "//tmp/my_file.tif"

raster_layer = QgsRasterLayer(file_path)

raster_name = Path(file_path).stem

parameters = {
    'EXPRESSION': f"{raster_name}@1 * 2",
    'LAYERS': [raster_layer],
    'OUTPUT': 'TEMPORARY_OUTPUT',
}

processing.runAndLoadResults("qgis:rastercalculator", parameters)
1
  • Thank you! Adding the layer to project feels a bit icky but seems like a decent workaround. The filename stem won't work because I might be a user who loves filenames like this (name is evil".tif and that would not work in expressions. I'll leave the question open for now, maybe there is some proper way. Jan 30, 2023 at 17:30

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.