I have a function who uses a layer already styled using another function and saves it as a gpkg and I want to save the style in that gpkg:

def saving_gpkg(styled_layer):
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.driverName = "GPKG"
    QgsVectorFileWriter.writeAsVectorFormatV2(styled_layer, "nice_filename", QgsCoordinateTransformContext(), options)
    styled_layer.saveStyleToDatabase("polygon", "style automatically created", True, "")

The gpkg is created, but if I open the created file, it doesn't have the defined style, just a random singlesymbol. I'm missing something?


If you want to save one or several layers in a geopackage, the easiest way is to use the package algorithm which has the SAVE_STYLES parameter which must be True if you want to save the styles that your layers have in the geopackage that will be generated.

filename = '/home/ai/Desktop/prueba.gpkg'
layers = [styled_layer]
processing.run("native:package", {'LAYERS': layers, 'OUTPUT': filename, 'OVERWRITE': False, 'SAVE_STYLES': True})

A working example based on your code. Be aware that my code scope is limited as I use a layer name without space for everything whereas I should sanitized it in particular for layername parameter reused in the GPKG. Most of the code logic is based on qgsalgorithmpackage.cpp C++ code used in Processing algorithm "Package layers" in the answer from @leo-cardona

def saving_gpkg(styled_layer, out_path):
    context = QgsProject.instance().transformContext()
    name = styled_layer.name()
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.layerName = name
    options.fileEncoding = styled_layer.dataProvider().encoding()
    options.driverName = "GPKG"
    QgsVectorFileWriter.writeAsVectorFormatV2(styled_layer, out_path, context, options)
    doc = QDomDocument();
    readWriteContext = context = QgsReadWriteContext()
    gpkg_layer = QgsVectorLayer(f"{out_path}|layername={name}", name, "ogr")
    gpkg_layer.saveStyleToDatabase(name, "", True, "")

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.