QGIS Styles – How to Load Multiple Styles on a Single Layer at Once in QGIS

qgisqml

I have a set of qml style files saved that I apply to similar layers across multiple projects. An example would be a linetype shapefile layer with about a dozen different styles; currently I have to repeat the process of adding a new style and loading the qml file for each of the different styles. Then I have to do it a few more times in that project and repeat the whole thing again in the next project.

Just trying to see if there's a way to load multiple style files on the same layer at once? Something like instead of browsing to a single qml, I could multi-select several qml files and load them at once?

Example of multiple styles per layer

Best Answer

You can load multiple styles using pyqgis script (explanations in comments):

import os
from qgis.core import QgsMapLayerStyle
from qgis.utils import iface

# set path to your styles here
qml_path = '/home/user/qml'

layer = iface.activeLayer()
style_manager = layer.styleManager()

# read valid style from layer
style = QgsMapLayerStyle()
style.readFromLayer(layer)

for qml_file in [f for f in os.listdir(qml_path)
                 if os.path.isfile(os.path.join(qml_path, f)) and
                 f.endswith('.qml')]:
    # get style name from file
    style_name = os.path.basename(qml_file).strip('.qml')
    # add style with new name
    style_manager.addStyle(style_name, style)
    # set new style as current
    style_manager.setCurrentStyle(style_name)
    # load qml to current style
    (message, success) = layer.loadNamedStyle(os.path.join(qml_path, qml_file))
    print message
    if not success:  # if style not loaded remove it
        style_manager.removeStyle(style_name)

You can run it in the QGIS python console or adapt to a processing script.

(Tested on current LTR version QGIS 2.18)

Related Question