PyQGIS – Adjust Print Layout Label Text Size in QGIS 3

pyqgispyqgis-3qgisqgis-3qgis-print-layouts

I'm adding a label to a Print Layout using python. I do so with the following code:

label = QgsLayoutItemLabel(layout)
label.setText("This is my map label")
label.adjustSizeToText()
layout.addLayoutItem(label)
layout.attemptMove(QgsLayoutPoint(0.25, 0.25, QgsUnitTypes.LayoutInches))   #repositions map label

The label is small font by default and I want to resize it, but cannot figure it out. After looking at the documentation for QgsLayoutItemLabel() there is no method to set the text label size.

The problem here is label.setText(), creates a string with the text. I could modify the size of the label but only if the string is some kind of text object?

In this example in the first answer, the person created a QgsPalLayerSettings() object, which he then formatted.

I found a helpful example in the source code for the QuickPrint plugin. The author gets user input via a dialog box using the following line:

titel = self.dlg.titelFld.text()

Here he converts this input to text using the text() method, but I can't figure out how to apply text() method to a string.

Any suggestions?

Best Answer

The QgsLayoutItemLabel class has a setFont method which takes a QFont object.

So you could try modifying your script like this:

label.setText("This is my map label")
label.setFont(QFont('Arial', 14)) #Change to your desired font and size
label.adjustSizeToText()

Depending on what your import statements look like, you may need to import QFont first like:

from PyQt5.QtGui import QFont