[GIS] Using Python to set text for a label in a QGIS3 print layout label

pyqgispyqgis-3qgis-3

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?

Best Answer

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
label.adjustSizeToText() 

#add map_label to your layout
layout.addLayoutItem(map_label)

#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().