QGIS Vector Layer – How to Load Style Files

pyqgisqgis

I'm having a .gdb file for a digital catastre, therefore i created .qml styles for the different lines, polygons and points. Is there a way to load them automatic when adding the vector?
I already saved the .qml styles in the same folder with the same name.

Best Answer

You can use PyQGIS and execute this code when you have added the layers.

It will find and store all styles files in a dictionary, with style file name as key and full path to the style file as value. Then apply each style file to the layer by matching style file name and layer name:

import os
style_file_folder = r'C:\GIS\data\Bakgrundskartor_LMV' #Adjust
style_files = {}
for root, folder, files in os.walk(style_file_folder): #Find all style files in folder and add to style_files dictionary
    for file in files:
        fullname = os.path.join(root, file)
        if file.endswith('.qml'):
            style_files[file.split('.')[0]]=fullname
#style_files is now: {'ak_riks': 'C:\\GIS\\data\\Bakgrundskartor_LMV\\ak_riks.qml', 'vl_riks': 'C:\\GIS\\data\\Bakgrundskartor_LMV\\vl_riks.qml'}

for layer in QgsProject.instance().mapLayers().values(): #For each file added to the map
    if layer.name() in style_files: #Find matching style file
        layer.loadNamedStyle(style_files[layer.name()]) #And apply it
        layer.triggerRepaint()

enter image description here

Related Question