I'm trying to programmatically generate new layers from a database, and then print them using a template. Using the QGIS 2.14.10x64
Python Console in Windows 7x64. I've been following on to code from this answer and this one. Set up code:
from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface
def load_print_composer(template):
'''Load a print composer template from provided filename argument
Args:
template: readable .qpt template filename
console: boolean if method is used in QGIS console
Returns:
myComposition: a QgsComposerView loaded from the provided template
--mapSettings: a QgsMapSettings object associated with myComposition'''
# Load template from filename
myDocument = QDomDocument()
with open(template, 'r') as templateFile:
myTemplateContent = templateFile.read()
myDocument.setContent(myTemplateContent)
composerView = None
composerView = iface.createNewComposer()
composerView.composition().loadFromTemplate(myDocument)
myComposition = composerView.composition()
mapSettings = myComposition.mapSettings()
return {'QgsComposition': myComposition,
'QgsMapSettings': mapSettings,
'QgsComposerView': composerView}
template = 'somefilename'
printcomposer = load_print_composer(template)
Things that don't work
#1 changing QgsMapSettings
:
layerlist = printcomposer['QgsMapSettings'].layers()
layer0 = layerlist.pop(0)
printcomposer['QgsMapSettings'].setLayers(layerlist)
#2 Making sure mapCanvases are linked
From this answer
map0 = printcomposer['QgsComposition'].getComposerMapById(0)
map0.renderModeUpdateCachedImage()
map0.setMapCanvas(iface.mapCanvas())
map0.layerSet()
map0.setLayerSet(layerlist)