6

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()
0

1 Answer 1

8

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()

1
  • Thanks again for your help CodeBard ! :)
    – wanderzen
    Commented Dec 12, 2022 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.