PyQGIS – How to Set Layer Styles with QML File from URL

pyqgisqmlstyleurlvector-layer

I was wondering how to import and apply a style from an URL to a layer with PyQGIS.

My first thought was to do this but it didn't workout :

import urllib
from urllib import request

vlayer = iface.activeLayer()

fp = urllib.request.urlopen('https://raw.githubusercontent.com/xxxxx/xxxxxx/main/layers_styles/my_layer_style.qml')

mybytes = fp.read()
test = mybytes.decode("utf8")

print(test)

vlayer.loadNamedStyle(test)
vlayer.triggerRepaint()

Best Answer

Instead of loadNamedStyle use the method importNamedStyle. It can directly receive a XML document as argument instead of a file path.

Creating an XML document is simply using QDomDocument::setContent() with the bytes you read from the URL.

import urllib
from urllib import request

vlayer = iface.activeLayer()

fp = urllib.request.urlopen('https://raw.githubusercontent.com/xxxxx/xxxxxx/main/layers_styles/my_layer_style.qml')

mybytes = fp.read()

document = QDomDocument()
document.setContent(mybytes)

res = vlayer.importNamedStyle(document)
print(res) # result contains potential error message when loading style fails
vlayer.triggerRepaint()