1

I'm looking for a way to iterate through items from a composer in QGIS 3, with pyQgis.

First I create a QgsPrintLayout and add it to the layouts manager in my project.

    self.newLayout = QgsPrintLayout(projet)
    self.newLayout.initializeDefaults()
    manager.addLayout(self.newLayout)

Then I load a template to populate the QgsPrintLayout

    doc=QtXml.QDomDocument()
    doc.setContent(file1, False)
    self.newLayout.loadFromTemplate(doc,QgsReadWriteContext())

And I want a list of all the QgsPrintLayout items:

    labels = [item for item in self.newLayout.layoutItems()\
    if item.type() == QgsComposerItem.ComposerLabel]  ...

But Qgis answers:

    labels = [item for item in self.newLayout.layoutItems()\
    AttributeError: 'QgsPrintLayout' object has no attribute 'layoutItems'

But in doc for QgsLayout (from which QgsPrintLayout takes a part of its methods), I can read:

void layoutItems (QList< T *> &itemList) const

Returns a list of layout items of a specific type. More...

And I really can't find another Public Member function to list all items from a QgsPrintLayer.

What am I missing here?

1 Answer 1

1

The docs also state that the layoutItems() method is not available in Python bindings, but you can use the inherited method .items() which comes all the way from the QGraphicsScene base class.

So you could do:

layout_items = [i for i in self.newLayout.items()]
print(layout_items)

If you are trying to access just the label items, QgsComposerItem.ComposerLabel is from the 2.18 API. Instead, you should do something like:

label_items = [j for j in self.newLayout.items() if isinstance(j, QgsLayoutItemLabel)]
print(label_items)

You could also set the id of a QgsLayoutItem with the setId() method then retrieve it directly with:

self.newLayout.itemById('IdString')

Where 'IdString' is whatever id you assigned to your item.

2
  • Thank you very much, using .items() and QgsLayoutItemLabel works perfectly! And now I know I can click on the method name in QGIS doc to see if it's available in the python bindings! ;-)
    – V Damoy
    Commented Nov 6, 2020 at 8:10
  • @V Damoy, you're welcome- glad it's working.
    – Ben W
    Commented Nov 7, 2020 at 1:59

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.