3

I am using a print composer from QGIS using python. Inside a QGIS project (.qgz, QGIS version 3.18.3), I created a print composer layout called "mylayout" and added a map and a legend. I would like to apply a QgsExpression with python to the "Soil cover" item of the legend (see image).

Expression I want to apply (Automatic wrap text (line break) in map composer legend)

wordwrap(@symbol_label, 30)

Current legend (left collapsed, right expanded)

enter image description here

Code

I created aQgsExpression and a QgsExpressionContext linked to the legend but I have no clue of what to do next.

# sample of init code 
manager = project_instance.layoutManager() # get layout manager from Qgis project
layout = manager.layoutByName("mylayout") # get existing layout in layout manager

# define expression and expression context
legend = layout.itemById("legend") # get legend from layout
legend.setAutoUpdateModel(False) # not sure about this one
exp = QgsExpression("wordwrap(@symbol_label, 30)") 
context = legend.createExpressionContext()

# I tried
exp.evaluate(context)

1 Answer 1

5

Try the code snippet below:

map_layer = QgsProject.instance().mapLayersByName('Soil cover')[0]
manager = QgsProject.instance().layoutManager()
layout = manager.layoutByName("Test Layout")
legend = layout.itemById("legend")
layer_node = legend.model().rootGroup().findLayer(map_layer)
legend.setAutoUpdateModel(True)
layer_node.setLabelExpression('wordwrap(@symbol_label, 30)')
layout.refresh()

You can see the results on my test layer and layout below (I used the expression 'wordwrap(@symbol_label, 10)')

enter image description here

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