Thursday, 16 August 2018

qgis - Multiple styles using pyqgis


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.



Answer



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



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...