title: Iteratively saving an image from a QGIS composition via Python
body: <p>I am trying to create a script that will use the layer arrangement in my QGIS project to iteratively output an image for each layer in a specified group. </p>
  
  <p>Essentially, I have series of layers, and a group (called 'animate') which has additional layers. At the start of my script it:</p>
  
  <ol>
  <li>Ensures all layers in the 'animate' group are toggled off (no visibility)</li>
  <li>For each layer in the group, start at the top and turn on its visibility</li>
  <li>Output an image</li>
  <li>Turn off the visible layer, move to the next, turn it on, and save a new image. Repeat.</li>
  </ol>
  
  <p>Below is the code I currently have; it successfully saves an image for each layer, and updates the layers' visibility in the UI...but the saved images are all the same (first in the group). It is not refreshing the rendered view after each layer update:</p>
  
  <pre><code>from PyQt4.QtCore import *
  from PyQt4.QtGui import *
  from qgis.core import *
  import qgis.utils
  
  root = QgsProject.instance().layerTreeRoot()
  animGroup = root.findGroup("animate")
  layerCount = len(animGroup.findLayers())
  
  mapRenderer = iface.mapCanvas().mapRenderer()
  c = QgsComposition(mapRenderer)
  c.setPlotStyle(QgsComposition.Print)
  dpi = c.printResolution()
  dpmm = dpi / 25.4
  width = int(dpmm * c.paperWidth())
  height = int(dpmm * c.paperHeight())
  x, y = 0, 0
  w, h = c.paperWidth(), c.paperHeight()
  
  c.setPaperSize(500, 250)
  c.setPrintResolution(72)
  composerMap = QgsComposerMap(c, x ,y, w, h)
  c.addItem(composerMap)
  
  # first turn off all layers in the group
  animGroup.setVisible(2)
  
  i = 0
  while i &lt;= layerCount - 1:
      # for each layer in the group, output an image
      animGroup.setIsMutuallyExclusive(1,i)
  
      image = QImage(QSize(width, height), QImage.Format_ARGB32)
      image.setDotsPerMeterX(dpmm * 1000)
      image.setDotsPerMeterY(dpmm * 1000)
      image.fill(0)
      imagePainter = QPainter(image)
      c.renderPage(imagePainter, 0 )
  
      print 'set group to: ' + str(i)
      image.save("~/frames/" + str(i) + ".png", "png")
      i += 1
      imagePainter.end()
  
  print "~*" * 20, "Done"
  </code></pre>
  
  <p>Now, if I wrap the entire thing in a loop...it works. But that initializes a new mapRenderer every time, which is very inefficient. I would like to initialize only one canvas and renderer, and simply update it. But I have had no luck using mapRender.refresh() or updateCanvas()</p>
  
  <p>Has anyone had any luck with something similar, or know where I might be going wrong?</p>
  
  <p>Thank you sincerely!</p>