Sunday, 3 November 2019

qgis - How to load a style from POSTGIS in PyQt


The thing is that I have four styles I have created in QGIS through the GUI and saved into a postgresql database.


I can see them in the table named layer_styles


I have seen similar questions asking to load from qml file, or even from a database, like that but it looks as if I need to get a styled layer before for get the style from it.


It's like I say or can I load the styles from database without a styled layer?


Anyway I don't know how must I do to get the styles and use it for another layers



Answer



Well, this is my try to load a style stored in Postgres database. QGIS saves the layers in a table called layer_styles The column I need is styleqml, so I need to make a query like that:



select styleqml from public.layer_styles;

There are another descriptive columns like stylename or description I can use for help to choose the properly style. I could do:


select stylename, description, styleqml from public.layer_styles;

I have used only styleqml column and I have stored all the records in a list


Finnally I only have to set the style in my layer like that:


self.vlayer.applyNamedStyle(mylist[n])

I show a snippet of my code. Sorry if there are mistakes or if I am saying any silliness, but it works for me:



self.loadStyles = QtSql.QSqlQuery(self.conexion)
self.listOfStyles=[]
if self.loadStyles:
self.loadStyles.exec_("SELECT styleqml FROM public.layer_styles")
while self.loadStyles.next():
self.listOfStyles.append(unicode(self.loadStyles.value(0)))
self.myStyle = self.listOfStyles[1] # 1 in my case
self.vlayer.applyNamedStyle(self.myStyle)

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...