# Automatically set PostGIS/QGIS style to a layer

I have a plugin for my users which allow them to create a spatial view for different layers. I have define a set of styles fitting the display I want to give. I would like to define these styles to the view automatically every-time a new view is created. I am currently using QGIS 2.14, PostGIS 2.3, PostgreSQL 9.5 and Python 3 with the psycopg2 library.

I thought about simply populating the layer_style table in the database, but without success.

Does anyone know how to do so ?

you would do the following: Worked for me inside my plugin for QGIS 2.14.15:

• get the current layer:

layer = iface.activeLayer()

• apply the qml file

and this should work. I store them in a folder inside the plugin folder.

• Thank you, I'll try that soon. However I would prefer to not have to store the syle locally, that way every new user opening the view would have the same style displayed, that's why I thought more to automatize the "Save style to database (define as default style)" function available in QGIS, I don't really understand how this function works (nor the structure of the qml that is stored). – GuiOm Clair Jun 7 '17 at 6:22
• @GuiOmClair the qml file is in xml format ( just open one in notpad++ or any other text editor). what i meant by "store inside the plugin folder" is, that you could ship your plugin with a folder which already contains your default styles and allow the user to overwrite them – LaughU Jun 7 '17 at 6:33
• I understand. About the qml I meant I didn't take time to explore its structure yet, and about the storing in the plugin, I'd say that it is going in opposite direction than the idea of a DB to store datas, even a style, locally. In any case I really would like a storing in the DB which would make that a change in the style would be applied for every user. In this regard it should be possible to fetch the qml from the DB instead of from the local folder. – GuiOm Clair Jun 7 '17 at 6:39
• in that case I missunderstood you my bad! – LaughU Jun 7 '17 at 6:48

I just realized that I made a simple little mistake in my piece of code which were not fulfilling properly the field f_table_schema, hence stopping my first idea to work. In case it can be of any help anyway, I just included and INSERT INTO public.layer_styles and inserted the desired values taken from a previous tuple in this table.