5

I have a QGIS python script which successfully loads a specified print composer template.

At the end of this script I have attempted to set the composer to the map canvas extent, but I receive the following error message:

AttributeError: 'QgsComposerView' object has no attribute 'getComposerItemById'

I'm running Windows 10, QGIS 2.14.7

The code is as follows:

import os,sys
from qgis.core import*
from PyQt4.QtCore import*
from qgis.utils import*
from qgis.gui import *
import qgis
from PyQt4.QtXml import *

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

myFile = os.path.join('P:\Office Admin\GIS\Templates\Plan templates\QGIS template plans\Title deed templates', 'A0_landscape_title deed.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
comp = iface.createNewComposer()
comp.composition().loadFromTemplate(myDocument)

map_item = comp.getComposerItemById('Map 1')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
1
  • Welcome to GIS:SE @Stuart! Try replacing map_item = comp.getComposerItemById('Map 1') with map_item = comp.composition().getComposerItemById('Map 1')
    – Joseph
    Commented Nov 7, 2016 at 12:25

1 Answer 1

3

Thanks Joseph, that worked perfectly. I've shown the completed code below for reference.

import os,sys
from qgis.core import*
from PyQt4.QtCore import*
from qgis.utils import*
from qgis.gui import *
import qgis
from PyQt4.QtXml import *

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

myFile = os.path.join('P:\Office Admin\GIS\Templates\Plan templates\QGIS template plans\Title deed templates', 'A0_landscape_title deed.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
comp = iface.createNewComposer()
comp.composition().loadFromTemplate(myDocument)

map_item = comp.composition().getComposerItemById('Map 1')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())

Note: If you do not set the Item ID in the "Item properties - Item ID" panel and save this as part of your template before running the code, the following error will occur:

Error: 'NoneType' object has no attribute 'setMapCanvas'

Your Item ID should correspond to that specified in the code - for this example the Item ID is Map 1.

1

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.