5

I have a print composer template which I'm trying to populate with different subset queries from a CSV-derived vector layer using the Python API. However, all the output PDFs contain everything except the layers on the map! I'm doing this with a standalone app, and it functions fine in that it does produce PDFs and the data is all loaded and interrogated just fine (I can subset query, count features etc.)

Here's the method I'm using to render the composition, as you can see I've tried to set the layers on the map in different places (actually there are 2 maps - one shows the extent rectangle of the other, but I can't get either to show anything) - this is my first QGIS scripting experience so I'm sure I'm missing something very obvious...

def compose(layers, species_binomial):
    # vlayer is the CSV vector layer, outline is the ADM0 country vector.
    vlayer, outline = layers

    # construct a QStringList for the renderer setLayerSet
    layers = QStringList(vlayer.id())
    layers.append(outline.id())

    # 1 maybe set the registry layers???
    QgsMapLayerRegistry.instance().addMapLayer(vlayer)
    QgsMapLayerRegistry.instance().addMapLayer(outline)

    # 2 maybe set the canvas layer???
    canvas = QgsMapCanvas()
    canvas.setExtent(outline.extent())
    canvas.setLayerSet([QgsMapCanvasLayer(outline), QgsMapCanvasLayer(vlayer)])

    # 3 set the renderer layers???
    renderer = canvas.mapRenderer()
    renderer.setLayerSet(layers)
    renderer.setExtent(outline.extent())

    composition = QgsComposition(renderer)
    with open(os.path.join(ROOT, 'species_composer.qpt'), 'rt') as fp:
        composer_template = fp.read()
    doc = QDomDocument()
    doc.setContent(composer_template)
    composition.loadFromTemplate(doc)

    # 4 maybe set the map layers of one of the maps???
    map1 = composition.composerMapItems()[1]
    map1.setLayerSet(layers)

    title = composition.getComposerItemById('title')
    title.setText(" ".join(species_binomial))  # this works fiiiine

    out_path = os.path.join(ROOT, 'out',  "%s_%s.pdf" % species_binomial)

    # make a lovely blank PDF with a title and a blue map rect
    ...

What am I doing wrong? Here's an example output...

PDF output from print composer template

  • I have the same doubt. Can anyone help? – Bárbara Duarte Jun 11 '15 at 15:54
  • Are you opening the project file you used to produce the map composer template you are using? – wided Jul 16 '15 at 15:11
  • @Steve Pike Did you ever figure this one out? I think I have the same issue. – user25976 Nov 4 '16 at 22:53

Your Answer

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

Browse other questions tagged or ask your own question.