[GIS] Loading layer styles; (*.qml file) is there a shortcut or toolbar icon

layersqgisstyle

Currently, to load a saved style you have to open the layer properties, scroll to the bottom and click on the style tab. As this is a regular thing I need to do when creating new maps I was wondering if I am missing and easier or quicker way to do this?
I have the layer styling window open all the time, but this window doesn't have access to the style button I need to load specific styles I regularly need when starting a new map.

Best Answer

We could create a new button on the toolbar which lets you choose a style to apply to the selected layer by writing some code into the Python Console. Open the console using Ctrl + Atl + P and then copy/paste the code below:

action = QAction(QIcon(""), "Load style for selected layer", iface.mainWindow())
action.setCheckable(False)
iface.addToolBarIcon(action)

def loadStyle(layer):
    layer = iface.activeLayer()
    filename, selected_filter = QFileDialog.getOpenFileName(None, "Select style file", "", "QGIS Layer Style File (*.qml *.QML)")
    if filename:
        layer.loadNamedStyle(filename)
        layer.triggerRepaint()

action.triggered.connect(loadStyle)

A new button should be made available on the toolbar. Select the layer you're interested in from the Layers Panel and then click the button which opens up a file browser:

Load style button from toolbar

Note that button will disappear when QGIS is restarted.


Edit:

If you want to avoid typing the code each time you load QGIS, you could consider creating a startup.py script which is executed each time QGIS is loaded. Assuming you are using QGIS 3, create a text file and save it as startup.py in the relevant directory. Use the same code as above but you must include the modules required. So your script should look like:

from qgis.utils import iface
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QFileDialog

action = QAction(QIcon("C:/Program Files/QGIS 3.8/apps/qgis/icons/qgis-qml.ico"), "Load style for selected layer", iface.mainWindow())
action.setCheckable(False)
iface.addToolBarIcon(action)

def loadStyle(layer):
    layer = iface.activeLayer()
    filename, selected_filter = QFileDialog.getOpenFileName(None, "Select style file", "", "QGIS Layer Style File (*.qml *.QML)")
    if filename:
        layer.loadNamedStyle(filename)
        layer.triggerRepaint()

action.triggered.connect(loadStyle)

New style icon