0

I'm trying to programmatically modify the upper and lower range values and the label on the graduated symbol renderer of a map layer, then producing a PDF from a layout based on that map.

The map item updates correctly to reflect changes in the upper and lower range values, but the legend item does not reflect changes I make to the labels.

I've tried all the triggerRepaint(), update(), legendUpdate(), etc. calls I could find but the only thing I found that made the legend update was setAutoUpdateModel(True), which has the unfortunate side-effect of making the legend include all the layers that I don't want to see a legend for. I'd even use that as a work-around if I could figure out how to programmatically hide the legend items I don't want.

What might I be missing or doing wrong?

3
  • I don't know if it will work and I can't test right now, but perhaps layer.emitStyleChanged() will do it.
    – Matt
    Feb 8 at 16:03
  • Thank you for the suggestion but unfortunately it had no effect.
    – Jonathan
    Feb 8 at 23:22
  • I finally found a work-around - write then re-open the project.
    – Jonathan
    Feb 8 at 23:35

1 Answer 1

0

I faced the same when did a standalone script for generating layouts and images from there. Modern pyqgis syntax may require resetting the whole symbology object. This was my case with classification method:

# define layer and its renderer
layer = iface.activeLayer()
renderer = layer.renderer()

# setting the classification method 
method = QgsClassificationEqualInterval()
method.setLabelPrecision(0)
method.setLabelFormat('%1 to %2')
renderer.setClassificationMethod(method)

renderer.updateClasses(layer_out, 5) # let there be five classes

# updating layer symbology, changes will be seen immediately in layout window
renderer.updateColorRamp()
renderer.updateRangeLabels()
layer.setRenderer(renderer)
layer.triggerRepaint()
layer.reload() 

# and one more optional method that I used before to see changes in layer treeview
iface.layerTreeView().refreshLayerSymbology(layer.id())

Other methods are listed here: https://api.qgis.org/api/qgsclassificationmethod_8h_source.html#l00092 and in another QGIS source code documentations

2
  • None of those calls produced anything for me(!) And as my real application runs QGIS headlessly I don't even have an iface to operate on.
    – Jonathan
    Feb 10 at 13:06
  • Yes, iface is unreachable from standalone script but its methods can be replaced. I suggest there are another methods for layer renderer that can be helpful Feb 10 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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