1

I have the same problem as this How to set up QGIS print composer options from the python console?

I have a composer template called "Template", I can open it with the python console but not edit the map content.

I'm very new to python so its likley to be something simple Ive overlooked. The ultimate aim is to loop through locations (from a shapefile) and create a map for each one with unique labels. I realise people have done similar things before, but none of my attempts have got them to work so I'm starting from scratch.

I'm using QGIS 2.8 on Windows 7.

from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtXml import *
import tempfile
import os

#test 
i=1

cLayer = iface.mapCanvas().currentLayer()
expr = QgsExpression( "\"ID\"=i" )
it = cLayer.getFeatures( QgsFeatureRequest( expr ) )
ids = [i.id() for i in it]
cLayer.setSelectedFeatures( ids )

canvas = qgis.utils.iface.mapCanvas()
canvas.zoomToSelected()

myFile = os.path.join('Z:\Output', 'Template.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
(True, u'', 0, 0)
newcomp = iface.createNewComposer()
newcomp.composition().loadFromTemplate(myDocument)
True
composition = QgsComposition(canvas.mapSettings())
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)
**Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'setMapCanvas'
map_item.zoomToExtent(canvas.extent())
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'zoomToExtent'***
  • 1
    Your initial statement says that you have the same problem as another question, and that question has two answers. So your question is answered. If it isn't answered, you should explain what the difference is. Otherwise your question is a duplicate which will just be closed as such. – BradHards Aug 16 '15 at 8:10
  • You may also want to have a look at the Atlas feature of QGIS which does pretty much what you want. – Matthias Kuhn Aug 16 '15 at 9:51
  • Yes, I was trying to reinvent the wheel, the atlas plugin is a gui version of exactly what I wanted to do, thanks – Johnny5 Aug 17 '15 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.