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

import processing
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'  

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

  • 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
    Commented Mar 23, 2018 at 13:12

2 Answers 2


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.


To save the style into a database use:

  • here database mean postgres , what if there are multiple database connected ? Commented Jun 28, 2018 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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