7

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.

asked Apr 5, 2018 at 19:26
4
  • changelog.qgis.org/en/qgis/version/3.0.0 Commented Apr 5, 2018 at 19:32
  • @csk, I didn't find anything about the question. Commented 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. Commented Apr 5, 2018 at 19:49
  • 1
    Be 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 crashes Commented Apr 5, 2018 at 19:58

1 Answer 1

11

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
78.6k57 gold badges260 silver badges407 bronze badges
answered Apr 6, 2018 at 3:21
1
  • @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? Commented Dec 7, 2021 at 2:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.