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.
-
changelog.qgis.org/en/qgis/version/3.0.0csk– csk2018年04月05日 19:32:56 +00:00Commented Apr 5, 2018 at 19:32
-
@csk, I didn't find anything about the question.Kadir Şahbaz– Kadir Şahbaz2018年04月05日 19:45:32 +00:00Commented Apr 5, 2018 at 19:45
-
I should have said, look at the changelog to see if that change is documented. If you already did that, edit your question to mention which sources you've already looked at. Otherwise people will waste their time and yours by suggesting solutions you've already tried.csk– csk2018年04月05日 19:49:37 +00:00Commented Apr 5, 2018 at 19:49
-
1Be careful doing this - you'll need to make sure your algorithm correctly returns the flag to indicate that it can't be run in the background thread, or you'll open the way for all sorts of crashesndawson– ndawson2018年04月05日 19:58:09 +00:00Commented Apr 5, 2018 at 19:58
1 Answer 1
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.
-
@KadirŞahbaz I came across this while trying to find a way to do this gis.stackexchange.com/questions/416542/… Were you able to find a way to do what you were doing, if yes, can you post your code here as an answer?ar-siddiqui– ar-siddiqui2021年12月07日 02:18:53 +00:00Commented Dec 7, 2021 at 2:18