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()
J. Monticolo
16k1 gold badge30 silver badges65 bronze badges
asked Dec 9, 2022 at 12:36
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()
answered Dec 9, 2022 at 21:37
1
  • Thanks again for your help CodeBard ! :) Commented Dec 12, 2022 at 8:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.