I'm really new to QGIS coding and I'm having a hard time finding (especially) the api classes/functions to carry out actions of the Query Builder window.

I'm basically trying to do this:

  1. Iterate from n=1 to 200...

  2. Query layerA where field_id = n

  3. Query layerB where field_id = n

  4. Query layerC where field_id = n

  5. Save as img_n.png

Pretty simple, I think, but it has become a real pain to do by hand in the GUI.

2 Answers 2


Well, on my own, I finally dug out the key function I needed: setSubsetString(). Whoever named this thing?...doesn't seem very intuitive as to its function.

Here's the skeleton I'm working with now:

canvas = qgis.utils.iface.mapCanvas()
allLayers = canvas.layers()
for n in range(1, 201)
    for layer in allLayers:
        layer.setSubsetString('field_id = ' + str(n))
    canvas.saveAsImage('img_' + str(n) + '.png')

  • setSubString filters, using the providers syntax, the lyaer. It is fine to use it but be aware the syntax might change if you change the layer type you are using.
    – Nathan W
    Feb 1, 2013 at 0:45
  • If people want to use this code more generically than I do, yes, they should check that the layer is type vector (QgsMapLayer::LayerType) and probably more checks along the way. Feb 1, 2013 at 21:22

I would suggest you to go through their API documentation.

Coming back to your question, you can iterate through all layers in the TOC using:

canvas = qgis.utils.iface.mapCanvas()
allLayers = canvas.layers()
for i in allLayers:
   print i.name()
   #Do other stuff here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.