I have created a blank print layout, now I want to add items to it like a map, legend, etc.

Here is my code so far to create a new print layout, this works just fine:

#This creates a new print layout
project = QgsProject.instance()                    
manager = project.layoutManager()
layout = QgsPrintLayout(project)
layout.setName('My Layout')                           

Now I want to add stuff to the layout, starting with a map:

map_item = QgsLayoutItemMap.create(layout)

But I get the following error: enter image description here

When I look at the documentation for QgsLayoutItemMap.create I see this, except I do not understand it: enter image description here

What does this mean "the caller takes responsibility for deleting the returned object" and how do I add a map (or other) objects to my Print Layout?


The correct approach looks somewhat like this:

    # create the map item
    map = QgsLayoutItemMap(layout)

    # setup its initial position on the page
    map.attemptSetSceneRect(QRectF(20, 20, 200, 100))

    # setup an initial extent to view in the map
    rectangle = QgsRectangle(-13838977, 2369660, -8672298, 6250909)

    # add the map to the layout
  • I diagnosed my issue which is the Print Layout wants a new name each time. so if I change the value in layout.setname() it works. In the documentation states: "The caller takes responsibility for deleting the returned object". So I need to remove the current print layout, to create one with the same name. Correct? A follow up on this, I don't see a "delete" or "remove" method (or equivalent) in the list of methods for QgsPrintLayout. Can I delete the current print layout? This probably deserves a separate question... – Erich Purpur Jan 18 '19 at 16:15
  • 1
    @ErichPurpur The layout can be removed using the LayoutManager object. These has functions clear() and removeLayout(). You can also use layoutByName to get the correct layout if multiple were loaded. See: qgis.org/pyqgis/3.0/core/Layout/… – Pepe Feb 17 '19 at 19:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.