Is there a way to write a print composer to a QGS project file via PyQGIS, so that when the project file is opened later, that print composer is available?

I am able to successfully do the following:

  • load and manipulate a project (load layers, etc)
  • load a print composer template (QPT file) and manipulate the composer elements
  • save the modified QGS file
  • export the print composer map to PDF

However, I can't figure out how to save that print composer to the QGS file.

Essentially that means that if I want to go into the QGS file afterwards and make edits to the map generated from the print composer, I need to load a new print composer from template and redo all the edits from scratch (map title, extents, map notes, etc).

The following code works to load a composer from a QPT template file and export the map as PDF, but does not save the composer with the QGS file:

#initialize QGIS
app = QgsApplication([], True)

#set project and template paths
project_path = "/mypath/myproject.qgs"
template_path = "/mypath/mytemplate.qpt"

#get canvas and load project
canvas = QgsMapCanvas()
project = QgsProject.instance()

#load print composer template
template_file = file(template_path)
template_content = template_file.read()

document = QDomDocument()
composition = QgsComposition(canvas.mapSettings())

#refresh after manipulating composer elements

#export to PDF and also save a QGS file

I believe I must be missing something either in, or prior to, the last line of code:


to add the composer to the QGS file.


1 Answer 1


QgsLayoutManager handles compositions stored directly in a project rather than as template files


#add a composition

#print composition names
for comp in comps:
    print ('Layout: {}'.format(comp.name()))

#load a composition by name
composition=layoutManager.compositionByName('My Composition')

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.