[Qgis-user] [QGIS-Developer] Loading multiple raster images from processing algorithm

Nyall Dawson nyall.dawson at gmail.com
Thu Mar 11 14:19:18 PST 2021


On Fri, 12 Mar 2021 at 07:26, C Hamilton <adenaculture at gmail.com> wrote:
>
> For one of my QIGS processing algorithms I have a destination folder, QgsProcessingParameterFolderDestination, where one or more GeoTIFF images are created. Once these images are created, how do I load them so that they display in QGIS from the "processAlgorithm" method? I had thought that this might work where I would iterate through each image created?

Definitely DON'T do this in the processAlgorithm method if your
algorithm is running in a background thread. It's not thread safe to
add layers to the main project from a background thread.

You could do it in a postProcessAlgorithm override though, as that is
guaranteed to run in the main thread. Just be ultra-cautious not to
store a layer created on the background thread and then try to access
this from postProcessAlgorithm -- layers have thread affinity to the
thread which created them, and can't just be accessed from any other
thread. To be safe you should always create a new layer from the
desired uri instead.

> path = path_to_the_image
> rlayer = QgsRasterLayer(path, name_of_image)
> QgsProject.instance().addMapLayer(rlayer, True)

also note that you should use context.project() instead of
QgsProject.instance() whenever you are accessing the project from a
processing algorithm -- this will ensure your algorithm works
correctly from the command line qgis_process tool!

Nyall


More information about the Qgis-user mailing list