예제 #1
0
    def fetch_and_apply_style(layer: QgsMapLayer,
                              url: str,
                              style_attr: str = '') -> Optional[str]:
        """
        Fetches a QML style from the specified URL, and applies it to a layer.
        @param layer: target layer to apply style to
        @param url: URL for QML content
        @param style_attr: optional str specifying name of existing field in layer to automatically
        update classified references to
        @return: Returns a str if an error occurred, or None if the fetch and apply was successful
        """
        request = QgsBlockingNetworkRequest()
        if request.get(QNetworkRequest(
                QUrl(url))) != QgsBlockingNetworkRequest.NoError:
            return 'Error while fetching QML style: {}'.format(
                request.errorMessage())

        reply = request.reply().content()
        tmp_file = QTemporaryFile('{}/XXXXXX.qml'.format(QDir.tempPath()))
        tmp_file.open()
        tmp_file_name = tmp_file.fileName()
        tmp_file.close()
        with open(tmp_file_name, 'wt', encoding='utf8') as f:
            f.write(reply.data().decode())

        layer.loadNamedStyle(tmp_file_name)

        if style_attr:
            StyleUtils.update_class_attribute(layer, style_attr)

        layer.triggerRepaint()
        return None
예제 #2
0
def update_symbology(layer: QgsMapLayer,
                     color: typing.Tuple[int, int, int] = None,
                     size: float = None,
                     file: str = None) -> None:
    assert layer, 'Layer is not defined'

    if file:
        assert isinstance(file, str)

        (msg, noError) = layer.loadNamedStyle(file)

        if not noError:
            raise Exception(msg)

    renderer = layer.renderer()

    symbol = None

    if isinstance(renderer, QgsSingleSymbolRenderer):
        symbol = renderer.symbol()
    elif isinstance(renderer, QgsGraduatedSymbolRenderer):
        symbol = renderer.sourceSymbol()
    else:
        raise Exception('Unknown renderer!')

    if color:
        assert isinstance(
            color, collections.abc.Sequence
        ), 'Color should be a iteratable of three numbers for Red, Green, Blue; Each of them between 0 and 255'
        assert len(color) in (
            3, 4
        ), 'There should be three numbers passed for Red, Green, Blue; Each of them between 0 and 255'

        symbol.setColor(QColor.fromRgb(*color))

    if size:
        # For lines
        if type(symbol) == QgsLineSymbol:
            symbol.setWidth(size)

        # For points
        if type(symbol) == QgsMarkerSymbol:
            symbol.setSize(size)

        layer.triggerRepaint()
        iface.layerTreeView().refreshLayerSymbology(layer.id())