I am converting several Plugins from QGIS 3 and I am struggling heavily with symbology and labeling. The straightforwart QGIS 2 approach seems to be totally gone. I found some help here:

Reading and setting label settings in PyQGIS 3?

But I can't figure out how to set the label-size to map Units, the QGIS2 approach was:

layer_loaded.setCustomProperty("labeling/fontFamily", "Arial")
layer_loaded.setCustomProperty("labeling/fontSize", "100")
layer_loaded.setCustomProperty("labeling/fontSizeInMapUnits", "true")

The new approach seems to be

layer_settings  = QgsPalLayerSettings()
text_format = QgsTextFormat()

text_format.setFont(QFont("Arial", 10))
text_format.setSize(100)
text_format.setSizeMapUnitScale(True) <-- wants a "QgsMapUnitScale"

layer_settings.setFormat(text_format)

layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
layer_loaded.setLabeling(layer_settings)

Is this the right approach?

up vote 1 down vote accepted

You need to call

textFormat.setSizeUnit(QgsUnitTypes.RenderMapUnits)

(see https://qgis.org/pyqgis/3.2/core/Text/QgsTextFormat.html#qgis.core.QgsTextFormat.setSizeUnit)

  • Thanks, works like a charm and improved my unterstanding of the documentation. (So text_format.setSizeMapUnitScale(QgsMapUnitScale) was completely unnecessary.) – AndreasK Nov 9 at 8:45
  • Yes, that's only necessary to set the map unit size limits. – ndawson Nov 9 at 19:21

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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