I am able to assign a QGIS 3.2 print layout label item to a Python variable using:

MyMapLabel = MyPrintLayoutObject.itemById('MyLabelName')

Which is all well and good but I need to be able to change the text of this label. In QGIS 2.18 this was possible using:

MyMapLabel = MyComposerObject.getComposerItemById('MyLabelName')
MyMapLabel.setText('A text string')

When trying the setText method in QGIS 3.2 the following error is returned:

AttributeError: 'QgsLayoutItem' object has no attribute 'setText'

I notice that QGIS 3 includes a new class QgsLayoutItemLabel but this is a constructor and doesn't seem to include a method for identifying existing label items.

Has anyone had more luck than I in interpreting the QGIS 3 Python API?

  • A workaround suggested by Nyall Dawson can be achieved using sip.cast(myLayoutItem, QgsLayoutItemLabel) Then the setText() method can be used. There must be a more appropriate solution though. Commented Aug 7, 2018 at 15:02

1 Answer 1


Try something like this. Keep in mind, you already need to have created a print layout

#create a layout item (a label in this case)
map_label = QgsLayoutItemLabel(layout)    

#set what the text will be
map_label.setText("This is a map label")

#change font style and size (optional)
map_label.setFont(QFont("Arial", 12))

#set size of label item. this step seems a little pointless to me but it doesn't work without it

#add map_label to your layout

#another thing you probably want to do is specify where your label is on the print layout
map_label.attemptMove(QgsLayoutPoint(0.25, 0.25, QgsUnitTypes.LayoutInches))

Here is the documentation page for class QgsLayoutItemLabel() where you can see all the class methods such as setFont(), setFontColor(). In this example I used one, setText().

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.