[QGIS-Developer] loading layer styles from PostGIS

Jo winfixit at gmail.com
Sun Apr 14 05:34:12 PDT 2019


I am trying to apply styles stored in a PostGIS DB.

In one method I'm trying to make an inventory, in the other method I try to
load the styles of a particular set for all layers.

I tried to find a solution using Google and this is the result of
assembling code using bits and pieces from other posts, but unfortunately
it still doesn't work.

def populate_layer_styles(self, layer):
    for style in layer.listStylesInDatabase()[2]:
        style_set = style[3]
        if style_set not in self.layer_styles:
            self.layer_styles[style_set] = {}
        style_manager = layer.styleManager()
        from PyQt5.QtXml import QDomDocument
        self.query = "SELECT styleqml FROM public.layer_styles WHERE
stylename='{}'".format(style)
        print(self.query)
        self.perform_query()
        styleqml = self.result[0]
        style_doc = QDomDocument()
        style_doc.setContent(styleqml)
        print(layer.importNamedStyle(style_doc))
        print(layer.loadNamedStyle(style))
        style_manager.addStyleFromLayer(style)

        self.layer_styles[style_set][style] = style_manager
    for style_set in self.layer_styles:
        if style_set not in self.dockwidget.rb_styles.button:
            self.dockwidget.rb_styles.add_button(str(style_set),
self.activate_style_set)

def activate_style_set(self, style_set):

    '''style_set is '1' or '2', etc'''
    print(style_set.text())
    for layer in QgsProject.instance().mapLayers().values():
        # only for vector layers
        if layer.type() != 0:
            continue
        # Extract table name using light regex
        table_re = re.compile(r'table="main"."(mow_.+?)"')
        table = table_re.search(layer.source())
        if table:
            table = table.group(1)
        else:
            continue
        # And compare it with layer names used for reloading the layers
        if table in self.tablenames:
            style = 'set' + style_set.text() + '-' + table
            print(style)
            print(layer.loadNamedStyle(style))
            style_manager = layer.styleManager()
            # style_manager.addStyleFromLayer(style)
            print(style_manager.mapLayerStyles())
            # print(style_manager.layer().name())
            print(style_manager.currentStyle())
            style_manager.setCurrentStyle(style)
            print(style_manager.currentStyle())
            print(layer.id())
            self.iface.layerTreeView().refreshLayerSymbology(layer.id())
    self.iface.mapCanvas().refreshAllLayers()

def reload_layers(self):
    self.iface.mapCanvas().layers()
    geometrycol = "geom"
    self.layer_styles = {}

    for l in QgsProject.instance().mapLayers():
        for table in self.tablenames:
            if l.title().lower().startswith(table):
                QgsProject.instance().removeMapLayer(l)
    for table in self.tablenames:
        uri = QgsDataSourceUri()
        uri.setConnection(DB_ADDRESS, DB_PORT, DB_NAME, DB_USERNAME,
DB_PASSWORD)
        uri.setDataSource("main", table, geometrycol)
        layer = QgsVectorLayer(uri.uri(False), table, "postgres")
        if not self.layer_styles:
            self.populate_layer_styles(layer)
        if not layer.isValid():
            QgsMessageLog.logMessage("Layer failed to load",
level=Qgis.Critical)
        else:
            QgsProject.instance().addMapLayer(layer)
            l = QgsProject.instance().layerTreeRoot().findLayer(layer)
            l.setExpanded(False)
            l.visibilityChanged.connect(self.update_layout_widgets)
            layer.geometryChanged.connect(self.update_layout_widgets)
            if layer.name().lower().startswith('mow_segment'):

QgsProject.instance().layerTreeRoot().findLayer(layer).setItemVisibilityChecked(False)
            layer.triggerRepaint()

Jo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20190414/7eca8686/attachment.html>


More information about the QGIS-Developer mailing list