1

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)
0

1 Answer 1

1

Confusing but functional, after muddling through Setting layer visibility in QGIS Python API?:

from qgis.gui import QgsMapCanvasLayer
map_registry = QgsMapLayerRegistry.instance()
names = [layer.name() for layer in map_registry.mapLayers().values()]
layerslist = [map_registry.mapLayersByName(names[0])[0],map_registry.mapLayersByName(names[1])[0]]
#what 
layerslist = [ QgsMapCanvasLayer(layer) for layer in layerslist]
iface.mapCanvas().setLayerSet(layerslist)
printcomposer['QgsComposition'].refreshItems()
1
  • Will update with standalone script when I get to it
    – raphael
    Commented Jan 11, 2017 at 19:39

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.