Tuesday, 4 August 2015

pyqgis - How to show a QgsComposition created in the QGIS Python console?


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?



Answer



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...