4

I wrote a script (for QGIS 3) that saves styles for all visible vector layers in QML and SLD files:

import processing
self=qgis.utils
layers = self.iface.mapCanvas().layers()

for layer in layers:
    layerType = layer.type()
    if layerType == QgsMapLayer.VectorLayer:
        name = layer.name()
        pathqml = 'C:/Style/QML/'+str(name)+'.qml'  
        pathsld = 'C:/Style/SLD/'+str(name)+'.sld'  
        layer.saveNamedStyle(pathqml)
        layer.saveSldStyle(pathsld)

How can I do this for the layers from SQLite, PostgreSQL/PostGIS ?

1
  • 1
    Are the sqlite and postgis layers not loaded into your Q project? Are you wanting to save those layer styles to a folder or to a database?
    – artwork21
    Mar 23 '18 at 13:12
1

To save the style into a database use:

layer.saveStyleToDatabase("NameOfStyle","Description",True,"uiFileContent")
1
  • here database mean postgres , what if there are multiple database connected ? Jun 28 '18 at 5:05
1

This is what i do to write all styles to the Postgresql database, after setting up a project:

Writing all styles to the database

mapGeometryType = {
    0: "Point",
    1: "Line",
    2: "Polygon",
    3: "UnknownGeometry",
    4: "NullGeometry",
}

layers = QgsProject.instance().mapLayers()

for layer in layers.values():
    if layer.type() == QgsMapLayer.VectorLayer:
        if mapGeometryType[layer.geometryType()] != "NullGeometry":
            layer.saveStyleToDatabase(name=layer.name(),description="Default style for {}".format(layer.name()), useAsDefault=True, uiFileContent="")

The code has an additional condition based on layer.geometryType() to avoid writing styles for non geographic data (from tables used just for joins or relations).

Styles are written on public.layer_styles table on the database where the layer comes from.

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.