2

I'm trying to develop a similar script to How to make serial maps from template?. I'd like to modify elements in the composition programmatically for each map that I want to print. In developing this I'd like to see the elements I'm modifying in the console without printing off the map. I was expecting to see a new print composer window open when I ran the below code from the QGIS console in 2.18.2, but nothing happens (no error message appears either).

from qgis.PyQt.QtXml import QDomDocument
def loadPrintComposerTemplate(template):
    '''Load a print composer template from provided filename argument

    Args:
        template: readable .qpt template filename

    Returns:
        myComposition: a QgsComposition loaded from the provided template
        mapSettings: a QgsMapSettings object associated with myComposition'''
    mapSettings = QgsMapSettings()
    myComposition = QgsComposition(mapSettings)
    # Load template from filename
    with open(template, 'r') as templateFile:
        myTemplateContent = templateFile.read()

    myDocument = QDomDocument()
    myDocument.setContent(myTemplateContent)
    return myComposition.loadFromTemplate(myDocument), mapSettings
composer, mapSet = loadPrintComposerTemplate(template)

Is this code correct? Is there a way to make the print composer appear? Is there a better way to test my code?

3

To open the new composer

from qgis.utils import iface
newcomp = iface.createNewComposer()

Load the template into the composer

newcomp.composition().loadFromTemplate(myDocument)

Has been taken from Here. Works in 2.18.2

  • Based on a reading of the documents one might think that loading the template into a QgsComposition and then using newcomp.setComposition(myComposition) would produce the same results. But I'm noting missing elements on the composer page, and the Items list is empty in the composer window – raphael Dec 30 '16 at 18:25
  • Also note that newcomp.composerWindow() has a hide() and show() method – raphael Jan 16 '17 at 16:51
4

The API has changed for QGIS3 :

from qgis.core import QgsComposition, QgsProject
composition = QgsComposition(QgsProject.instance())
composition.loadFromTemplate(template_qdoc)

Your Answer

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

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