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 there a way to make the print composer appear?

2 Answers 2

4

The API has changed for QGIS3 :

from qgis.core import QgsComposition, QgsProject
composition = QgsComposition(QgsProject.instance())
composition.loadFromTemplate(template_qdoc)
2
  • 1
    QgsComposition is not available anymore in recent qgis releases
    – luca76
    Jul 20, 2020 at 12:22
  • do you know to which class it was changed, @luca76? Jul 24 at 8:39
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

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, 2016 at 18:25
  • Also note that newcomp.composerWindow() has a hide() and show() method
    – raphael
    Jan 16, 2017 at 16:51

Your Answer

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

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