3

Reading the documentation I do not understand how the the row in layer_styles is specified (and why a table name has to be given)...

layer.loadNamedStyleFromDatabase('/path/to/geopackage/','layer_styles', 'styleName')

... doesn't do the trick.

2
  • It seems this method doesn't accept three parameters:TypeError: QgsMapLayer.loadNamedStyleFromDatabase(): too many arguments
    – aurel_nc
    Jul 3 '20 at 20:43
  • Only db and uri loadNamedStyleFromDatabase(self, db: str, uri: str) → Tuple[bool, str] see python doc here:qgis.org/pyqgis/3.0/core/Map/…
    – aurel_nc
    Jul 3 '20 at 20:46
1

I found a way to load the default style of the layer [here][1] (for PostGIS) and it's working on a geopackage. (For QGIS 3.X version (3.14 tested))

from qgis.PyQt.QtXml import QDomDocument

layer = iface.mapCanvas().currentLayer()
listedStyles = layer.listStylesInDatabase()
numberOfStyles = listedStyles[0]
defaultStyleId = listedStyles[1][0]
# defaultStyleName = listedStyles[2][0]
# defaultStyleDate = listedStyles[3][0]
if numberOfStyles > 0:
    styledoc = QDomDocument()
    styleTuple = layer.getStyleFromDatabase(defaultStyleId)
    styleqml = styleTuple[0]
    styledoc.setContent(styleqml)
    layer.importNamedStyle(styledoc)
    layer.triggerRepaint()

If you want a spécific style, you can find it in the tuple of lists made by layer.listStylesInDatabase() that is returning:

  • first, the number of styles linked to your layer and saved in the geopackage;

  • the list of styles' id;

  • the list of styles' name;

  • the list of styles' date; you have to iterate over the list of styles' name, then pick the style's id you need.

      from qgis.PyQt.QtXml import QDomDocument    
      layer = iface.mapCanvas().currentLayer()
      listedStyles = layer.listStylesInDatabase()
      numberOfStyles = listedStyles[0]
      if numberOfStyles > 0:
          i = 0
          for name in listedStyles[2]:
              if name == "buildings_old":
                  styleId = listedStyles[1][i]
                  styledoc = QDomDocument()
                  styleTuple = layer.getStyleFromDatabase(styleId)
                  styleqml = styleTuple[0]
                  styledoc.setContent(styleqml)
                  layer.importNamedStyle(styledoc)
                  layer.triggerRepaint()
              i+=1
    
    
    [1]: https://gis.stackexchange.com/questions/91429/pyqgis-loading-layer-style-with-postgis/371589#371589
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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