[GIS] Interactive “for each item in … do …” in QGIS

batchqgis

How does one interactively run a basic looping batch construct in QGIS?

for each {feature} in {features}:
    do {thing} with/to {feature}
    save/export/display {result}

Where:

  • {features} could be a polygon shapefile, a table, a selected record set, …
  • {feature} an individual record from {features}
  • {thing} is any Processing tool (or menu action?)

In ArcGIS cursors, batch processing, and model iterators can be brought to bear for looping, though only the latter are interactive. What are the QGIS equivalents?

Most of the topics and tutorials I've looked at so far involve shell scripts or straight up python code — meaning little to no interactivity and dynamism. Is this really the best/only way, at present? Essentially, I'm re-asking Interactive "For each …. Do" loop? and hoping for a QGIS specific answer.

Best Answer

Some more quality time with a search engine and different keywords finally dropped me on the doorstep of the right learning lab (I did hunt through the docs earlier, honest!):

Chapter 17, The QGIS processing guide of the QGIS Training Manual contains Iterative execution of algorithms, which finally revealed to me the magic "Iterate over this layer" button, present on all processing tool dialogs:

iterate button

When activated it automatically redirects the process to work on each feature within the layer, furthermore it also only operates on the selected features. Except for the ability to control the names for the outputs of each operation this perfectly suits the need which spawned this question. Beautiful.

Using only selected features is optional:

Processing >> Options


To round things out there is also the Python Console, activated from the Plugins menu, where can call the processing tools. It's wordy and a bit unwieldy (I've been spoiled by ArcGIS python console's interactive parameter hints) but very workable.

>>> import processing as processing
>>> processing.runalg(name_of_the_algorithm, param1, param2, ..., paramN,
         Output1, Output2, ..., OutputN)

To save repetitive strain I deal with the wordy part by using import processing as p or as pr instead.

I looked for but did not find the console syntax for the equivalent of pushing the iterate button when using runalg() -- a p.runalg(... iterative=yes). From Additional functions for handling data it likely has something to do with getfeatures(layer).

Related Question