QGIS Processing – Getting LayerTree Reference in Processing Script in QGIS 3

qgisqgis-3qgis-processing

Let's say my algorithm returns many layers and I need to insert those layers into the specific index in layer list, while running algorithm.

QgsProject.instance().layerTreeRoot() worked in QGIS 2 and I could change layers indexes as described in QGIS Layer Tree API (Part 2), while Processing algorithm was running.

How can I do the same thing in QGIS 3 Processing script?

I took a glance at QgsProcessingAlgorithm Class Reference. There are some functions like parameterAs****(). I thought one of them could help me. But I couldn't find useful function. I can get layer, layer list, crs etc. by means of some. But I can't get the layer tree (layerTreeRoot) or the project (QgsProject) reference.

Best Answer

It will be possible in 3.2 in standard algorithms through the use of QgsProcessingLayerPostProcessorInterface.

For 3.0, you'll need to grab the project's layer tree from context.project().layerTreeRoot() and manipulate it directly. But be aware that this isn't safe to do in anything but the main thread, so in 3.0 where there's no concept of layer post-processors (which run in the main thread) you'll need to tag your whole algorithm as thread-unsafe, by returning the QgsProcessingAlgorithm.FlagNoThreading flag in your algorithm's flags() implementation.

Related Question