5

I'm trying to automate adding styles to layers, with each layer having multiple styles using pyqgis.

Couldn't find any answers except this unanswered question:

Adding multiple styles to single layer with pyQGIS?

I did manage to add multiple styles using QgsMapLayerStyleManager:

layer = iface.activeLayer()
layer.name()
mlsm = QgsMapLayerStyleManager(layer)
layer.loadNamedStyle('~/Styles/BasinAnalysis/Area/Total.qml')
mlsm.renameStyle("default","Area-Total")
mlsm.addStyleFromLayer("Area-Freshwater")
layer.loadNamedStyle('~/Styles/BasinAnalysis/Area/Freshwater.qml')
mlsm.addStyleFromLayer("Area-Unirrigated")
layer.loadNamedStyle('~/Styles/BasinAnalysis/Area/Unirrigated.qml')
etc...

It seems like the multiple styles are associated to layer, and I can also see the changes applies to layer:

mlsm.styles()
>>> ['Area-Freshwater', 'Area-Other', 'Area-Saline', 'Area-TWW', 'Area-Total', 'Area-Unirrigated']

The problem is that styles don't appear when I right click on Layer -> Styles, it only shows the default layer.

I'm guessing I need to associate the styles from the StyleManager back to the layer, but not sure how.

1 Answer 1

4

You should obtain the style manager from layer instead of creating new one. You can do this with:

layer.styleManager()

You can read more in QGIS documentation: https://qgis.org/api/classQgsMapLayer.html#ac7ce04c009ac81926b63af4c98bd5c72

0

Your Answer

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

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