TransWikia.com

Load and apply Style from Postgres in QGIS 3

Geographic Information Systems Asked by Simu on November 13, 2020

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?

2 Answers

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)

Answered by Jochen Schwarze on November 13, 2020

Thanks for the clue.

I'm then loading a style from PostGIS like this:

uri_prod.setDataSource('public', 'layer_styles', None)
styles = QgsVectorLayer(uri_prod.uri(False), 'layer_styles', "postgres")
styleqml = ""
for style in styles.getFeatures():
    if style['f_table_schema'] == 'my_schema' and style['f_table_name'] == 'my_layer_name':
        styleqml = style['styleqml']

styledoc = QDomDocument()
styledoc.setContent(styleqml)
my_layer.importNamedStyle(styledoc)

And my_layer had the style expected.

Answered by aurel_nc on November 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP