6

I want to write a plugin in QGIS3 that changes the style of a vector layer. The styles to be loaded are saved in a postgres database in the table 'layer_styles'.

I read here or here , to use applyNamedStyle() which is not available anymore in QGIS3.

Therefore, I tried using loadNamedStyle():

uri=QgsDataSourceUri()
uri.setConnection("host_name", "5432", "database_name", "user", "xxx")    
uri.setSchema("public")
uri.setSql("SELECT styleqml FROM public.layer_styles WHERE stylename='nice'")
self.layer.loadNamedStyle(uri.uri(False)) 

This doesn't give me an error but nothing happens.

Do I only 'load' the style and not apply it?

My layer is of class QgsVectorLayer, could this be the problem?

Is there another way of loading and applying the style to the vector layer?

3

What happens if you do

iface.mapCanvas().refreshAllLayers()

and/or

iface.layerTreeView().refreshLayerSymbology(the_layer.id())

after your loadNamedStyle() ?

The method applyNamedStyle() in QGIS2 has been replaced by importNamedStyle() in QGIS3, cp. QGIS API Documentation > Backwards incompatible changes https://qgis.org/api/api_break.html

importNamedStyle() expect a QDomDocument as input (https://qgis.org/api/classQgsMapLayer.html#a59f50a11ff98460ac9e6c8993bff6295), so assumed you have your styleqml (String) selected from the layer_styles table you can import the style as follows:

from PyQt5.QtXml import QDomDocument
styledoc = QDomDocument()
styledoc.setContent(styleqml) 
the_layer.importNamedStyle(styledoc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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