Example #1
2
    def testRenderLineLayerDataDefined(self):
        """ test that rendering a line symbol with data defined enabled layer works"""

        lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp')
        lines_layer = QgsVectorLayer(lines_shp, 'Lines', 'ogr')
        QgsProject.instance().addMapLayer(lines_layer)

        layer = QgsSimpleLineSymbolLayer()
        layer.setDataDefinedProperty(QgsSymbolLayer.PropertyLayerEnabled, QgsProperty.fromExpression("Name='Highway'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setWidth(5)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)
        lines_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-133, 22, -70, 52))
        ms.setLayers([lines_layer])

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_linelayer_ddenabled')
        self.assertTrue(renderchecker.runTest('linelayer_ddenabled'))
        QgsProject.instance().removeMapLayer(lines_layer)
    def testHashPlacement(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Vertex)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(7)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_vertex', 'line_hash_vertex', rendered_image)

        s.symbolLayer(0).setPlacement(QgsTemplatedLineSymbolLayerBase.FirstVertex)

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_first', 'line_hash_first', rendered_image)

        s.symbolLayer(0).setPlacement(QgsTemplatedLineSymbolLayerBase.LastVertex)

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_last', 'line_hash_last', rendered_image)
    def testLineOffset(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())

        s.symbolLayer(0).setOffset(3)
        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_offset_positive', 'line_offset_positive', rendered_image)

        s.symbolLayer(0).setOffset(-3)
        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_offset_negative', 'line_offset_negative', rendered_image)
Example #4
0
    def testRenderLineLayerDisabled(self):
        """ test that rendering a line symbol with disabled layer works"""
        layer = QgsSimpleLineSymbolLayer()
        layer.setEnabled(False)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('LineString (0 0,3 4,4 3)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image))
    def testSimpleLineWithOffset(self):
        """ test that rendering a polygon with simple line symbol with offset results in closed line"""
        layer = QgsSimpleLineSymbolLayer()
        layer.setOffset(-1)

        symbol = QgsFillSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0))')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.geometry().boundingBox()
        # buffer extent by 10%
        extent = extent.buffer((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(self.imageCheck('symbol_layer', 'fill_simpleline_offset', image))
    def testRingFilter(self):
        # test filtering rings during rendering
        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.AllRings)
        s.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        s2 = s.clone()
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        doc = QDomDocument()
        context = QgsReadWriteContext()
        element = QgsSymbolLayerUtils.saveSymbol('test', s, doc, context)

        s2 = QgsSymbolLayerUtils.loadSymbol(element, context)
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        # rendering test
        s3 = QgsFillSymbol()
        s3.deleteSymbolLayer(0)
        s3.appendSymbolLayer(
            hash_line.clone())
        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)

        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('hashline_exterioronly', 'hashline_exterioronly', rendered_image)

        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.InteriorRingsOnly)
        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('hashline_interioronly', 'hashline_interioronly', rendered_image)
    def testSimpleLineUnitPixel(self):
        symbol = QgsSimpleLineSymbolLayer(QColor("black"), 1)
        symbol.setCustomDashVector([10, 10])
        symbol.setUseCustomDashPattern(True)
        symbol.setOffset(5)
        symbol.setOutputUnit(QgsUnitTypes.RenderPixels)
        dom, root = self.symbolToSld(symbol)

        # print ("Simple line px: \n" + dom.toString())

        self.assertStrokeWidth(root, 1, 1)
        self.assertDashPattern(root, 4, '10 10')
        self.assertStaticPerpendicularOffset(root, '5')
    def testHashAverageAngle(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.CentralPoint)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(7)
        hash_line.setHashAngle(45)
        hash_line.setAverageAngleLength(30)

        s.appendSymbolLayer(hash_line.clone())

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_center_average_angle', 'line_hash_center_average_angle', rendered_image)
    def testSimpleLineUnitDefault(self):
        symbol = QgsSimpleLineSymbolLayer(QColor("black"), 1)
        symbol.setCustomDashVector([10, 10])
        symbol.setUseCustomDashPattern(True)
        symbol.setOffset(5)
        dom, root = self.symbolToSld(symbol)

        # print ("Simple line px: \n" + dom.toString())

        self.assertStrokeWidth(root, 1, 4)
        self.assertDashPattern(root, 4, '36 36')
        self.assertStaticPerpendicularOffset(root, '18')
    def testQgsSimpleLineSymbolLayer(self):
        """
        Create a new style from a .sld file and match test
        """
        mTestName = "QgsSimpleLineSymbolLayer"
        mFilePath = QDir.toNativeSeparators("%s/symbol_layer/%s.sld" % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSimpleLineSymbolLayer.createFromSld(
            mDoc.elementsByTagName("LineSymbolizer").item(0).toElement()
        )

        mExpectedValue = type(QgsSimpleLineSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = "#aa007f"
        mValue = mSymbolLayer.color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 1.26
        mValue = mSymbolLayer.width()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.RoundCap
        mValue = mSymbolLayer.penCapStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.MiterJoin
        mValue = mSymbolLayer.penJoinStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = True
        mValue = mSymbolLayer.useCustomDashPattern()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = [5.0, 2.0]
        mValue = mSymbolLayer.customDashVector()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
    def testPointNumInterval(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())

        s.symbolLayer(0).setDataDefinedProperty(QgsSymbolLayer.PropertyLineDistance, QgsProperty.fromExpression(
            "@geometry_point_num * 2"))

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_dd_size', 'line_dd_size', rendered_image)
Example #12
0
    def testRenderLineLayerDisabled(self):
        """ test that rendering a line symbol with disabled layer works"""
        layer = QgsSimpleLineSymbolLayer()
        layer.setEnabled(False)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('LineString (0 0,3 4,4 3)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(
            self.imageCheck('symbol_layer', 'symbollayer_disabled', image))
    def testSimpleLineWithOffset(self):
        """ test that rendering a polygon with simple line symbol with offset results in closed line"""
        layer = QgsSimpleLineSymbolLayer()
        layer.setOffset(-1)

        symbol = QgsFillSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0))')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(
            self.imageCheck('symbol_layer', 'fill_simpleline_offset', image))
    def testRingFilter(self):
        # test filtering rings during rendering

        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)
        s.appendSymbolLayer(
            QgsSimpleLineSymbolLayer(color=QColor(255, 0, 0), width=2))
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.AllRings)
        s.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        s2 = s.clone()
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        doc = QDomDocument()
        context = QgsReadWriteContext()
        element = QgsSymbolLayerUtils.saveSymbol('test', s, doc, context)

        s2 = QgsSymbolLayerUtils.loadSymbol(element, context)
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        # rendering test
        s3 = QgsFillSymbol()
        s3.deleteSymbolLayer(0)
        s3.appendSymbolLayer(
            QgsSimpleLineSymbolLayer(color=QColor(255, 0, 0), width=2))
        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)

        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('simpleline_exterioronly', 'simpleline_exterioronly', rendered_image)

        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.InteriorRingsOnly)
        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('simpleline_interioronly', 'simpleline_interioronly', rendered_image)
Example #15
0
    def defStyle(self, layer):
        #
        # fs=l.renderer().rootRule().children()[1].symbols()[0]
        # sl ==> QgsSimpleLineSymbolLayer
        # sl=fs.symbolLayers()[0]
        # symbol = QgsSymbol.defaultSymbol(layer.geometryType())
        # Exporterle Style (.qml) pour determiner les attributs
        symb_def = {
            'color': '53,227,47,77',
            'joinstyle': 'bevel',
            'outline_color': '0,0,0,255',
            'outline_style': 'dash',
            'outline_width': '0.5',
            'outline_width_unit': 'MM',
            'style': 'solid'
        }
        symbol = QgsFillSymbol.createSimple(symb_def)
        renderer = QgsRuleBasedRenderer(symbol)
        root_rule = renderer.rootRule()
        rule = root_rule.children()[0]
        rule.setLabel("Valide")
        rule.setFilterExpression(
            "\"valide\" is not null and \"supprime\" is null")
        # root_rule.appendChild(rule)

        symb_def = {
            'capstyle': 'square',
            'customdash': '5;2',
            'customdash_unit': 'MM',
            'customdash_unit': '0',
            'line_style': 'dash',
            'line_color': '200,194,194,255',
            'joinstyle': 'bevel',
            'line_width': '0.80',
            'line_width_unit': 'MM',
            'offset': '0',
            'use_custom_dash': '1'
        }
        symbol = QgsFillSymbol.createSimple(symb_def)

        symbol.changeSymbolLayer(0, QgsSimpleLineSymbolLayer.create(symb_def))

        rule = QgsRuleBasedRenderer.Rule(symbol)
        rule.setLabel("En attente")
        rule.setFilterExpression("\"valide\" is null and \"supprime\" is null")
        root_rule.appendChild(rule)

        layer.setRenderer(renderer)
    def testOpacityWithDataDefinedColor(self):
        line_shp = os.path.join(TEST_DATA_DIR, 'lines.shp')
        line_layer = QgsVectorLayer(line_shp, 'Lines', 'ogr')
        self.assertTrue(line_layer.isValid())

        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)
        hash_line = QgsHashedLineSymbolLayer(True)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setDataDefinedProperty(QgsSymbolLayer.PropertyStrokeColor, QgsProperty.fromExpression(
            "if(Name='Arterial', 'red', 'green')"))

        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        line_symbol.setOpacity(0.5)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)
        s.appendSymbolLayer(hash_line.clone())

        # set opacity on both the symbol and subsymbol, to test that they get combined
        s.setOpacity(0.5)

        line_layer.setRenderer(QgsSingleSymbolRenderer(s))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-118.5, 19.0, -81.4, 50.4))
        ms.setLayers([line_layer])

        # Test rendering
        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_hashline')
        renderchecker.setControlName('expected_hashline_opacityddcolor')
        res = renderchecker.runTest('expected_hashline_opacityddcolor')
        self.report += renderchecker.report()
        self.assertTrue(res)
Example #17
0
def create_preview_vector_layer(image):
    marker_line = QgsSimpleLineSymbolLayer(color=QColor(110, 88, 232, 100), width=1)
    # FIXME: Save this to a uuid.gpkg file in user-defined dir or project dir
    vlayer = QgsVectorLayer("MultiPolygon?crs=EPSG:4326", "Footprints", "memory")
    vlayer.renderer().symbol().changeSymbolLayer(0, marker_line)
    dp = vlayer.dataProvider()

    qgs_fields = [
        QgsField("item_id", QVariant.String),
        QgsField("item_type", QVariant.String),
        QgsField("search_query", QVariant.String),
        QgsField("sort_order", QVariant.String),
    ]

    for prop in image["properties"]:
        qgs_fields.append(QgsField(str(prop), QVariant.String))

    dp.addAttributes(qgs_fields)
    return vlayer
Example #18
0
    def categorize_line_layer(self, layer=None, attr='FID_1', layer_name=None):
        """
        :param attr:
        :return:
        """
        if not layer:
            layer = self.get_layer_by_name(layer_name)
        try:
            attr_idx = layer.fields().indexFromName(attr)
        except:
            print('Could not get attr_idx, using 0.. correct?')
            attr_idx = 0
        unique_values = layer.uniqueValues(attr_idx)

        categories = []

        color_map = {0: '0, 0, 0', 1: '21, 153, 137'}
        color_map_hex = {0: '#000000', 1: '#159989'}
        for value in unique_values:
            symbol = QgsSymbol.defaultSymbol(layer.geometryType())

            # configure a symbol layer
            layer_style = {'color': color_map[value],
                           'outline': color_map_hex[value]}
            symbol_layer = QgsSimpleLineSymbolLayer.create(layer_style)

            # replace default symbol layer with the configured one
            if symbol_layer is not None:
                symbol.changeSymbolLayer(0, symbol_layer)

            # create renderer object
            category = QgsRendererCategory(value, symbol, str(value))
            # entry for the list of category items
            categories.append(category)

        # create renderer object
        renderer = QgsCategorizedSymbolRenderer(attr, categories)

        # assign the created renderer to the layer
        if renderer is not None:
            layer.setRenderer(renderer)

        layer.triggerRepaint()
Example #19
0
    def testSimpleLineWithCustomDashPatternHairline(self):
        """ test that rendering a simple line symbol with custom dash pattern"""
        layer = QgsSimpleLineSymbolLayer(QColor(0, 0, 0))
        layer.setWidth(0)
        layer.setCustomDashVector([3, 3, 2, 2])
        layer.setUseCustomDashPattern(True)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('LineString (0 0, 10 0, 10 10, 0 10, 0 0)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(
            self.imageCheck(
                'symbol_layer_simpleline_customdashpattern_hairline',
                'simpleline_customdashpattern_hairline', image))
Example #20
0
    def testRingFilter(self):
        # test filtering rings during rendering
        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.AllRings)
        s.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)
        self.assertEqual(s.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        s2 = s.clone()
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        doc = QDomDocument()
        context = QgsReadWriteContext()
        element = QgsSymbolLayerUtils.saveSymbol('test', s, doc, context)

        s2 = QgsSymbolLayerUtils.loadSymbol(element, context)
        self.assertEqual(s2.symbolLayer(0).ringFilter(), QgsLineSymbolLayer.ExteriorRingOnly)

        # rendering test
        s3 = QgsFillSymbol()
        s3.deleteSymbolLayer(0)
        s3.appendSymbolLayer(
            hash_line.clone())
        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)

        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('hashline_exterioronly', 'hashline_exterioronly', rendered_image)

        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.InteriorRingsOnly)
        g = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))')
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('hashline_interioronly', 'hashline_interioronly', rendered_image)
 def setStyleLayer(self, layer):
     if self.dlg.checkBox_mask.isChecked():  # only border
         if layer.geometryType(
         ) == QgsWkbTypes.PolygonGeometry or layer.geometryType(
         ) == QgsWkbTypes.LineGeometry:
             properties = {
                 'color': self.mColor.name(),
                 'outline_width': '0.6'
             }
             symbol_layer = QgsSimpleLineSymbolLayer.create(properties)
             layer.renderer().symbols(
                 QgsRenderContext())[0].changeSymbolLayer(0, symbol_layer)
         elif layer.geometryType() == QgsWkbTypes.PointGeometry:
             properties = {
                 'size': '2',
                 'color': self.mColor.name(),
                 'outline_color': self.mColor.name(),
                 'outline_width': '0.6'
             }
             symbol_layer = QgsSimpleMarkerSymbolLayer.create(properties)
             layer.renderer().symbols(
                 QgsRenderContext())[0].changeSymbolLayer(0, symbol_layer)
     else:
         if self.colorIndex > (len(self.colorValues) - 1):
             self.colorIndex = 0
         color = QColor(self.colorValues[self.colorIndex])
         self.colorIndex += 1
         if layer.geometryType() == QgsWkbTypes.PolygonGeometry:
             layer.renderer().symbols(
                 QgsRenderContext())[0].symbolLayer(0).setStrokeWidth(0.4)
             layer.renderer().symbols(
                 QgsRenderContext())[0].symbolLayer(0).setBrushStyle(
                     Qt.Dense4Pattern)
             layer.renderer().symbols(
                 QgsRenderContext())[0].symbolLayer(0).setFillColor(color)
             layer.setFeatureBlendMode(13)
     self.iface.layerTreeView().refreshLayerSymbology(layer.id())
Example #22
0
    def testSimpleLineWithCustomDashPattern(self):
        """ test that rendering a simple line symbol with custom dash pattern"""
        layer = QgsSimpleLineSymbolLayer(QColor(0, 0, 0))
        layer.setWidth(0.5)
        layer.setCustomDashVector([2, 5])
        layer.setUseCustomDashPattern(True)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('LineString (0 0, 10 0, 10 10, 0 10, 0 0)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(self.imageCheck('symbol_layer_simpleline_customdashpattern', 'simpleline_customdashpattern', image))
Example #23
0
    def testSegmentCenter(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.SegmentCenter)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())

        g = QgsGeometry.fromWkt('LineString(0 0, 10 0, 0 10)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_segmentcenter', 'line_hash_segmentcenter', rendered_image)
Example #24
0
    def testHashPlacement(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Vertex)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(7)
        hash_line.setAverageAngleLength(0)

        s.appendSymbolLayer(hash_line.clone())

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_vertex', 'line_hash_vertex',
                               rendered_image)

        s.symbolLayer(0).setPlacement(
            QgsTemplatedLineSymbolLayerBase.FirstVertex)

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_first', 'line_hash_first',
                               rendered_image)

        s.symbolLayer(0).setPlacement(
            QgsTemplatedLineSymbolLayerBase.LastVertex)

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_hash_last', 'line_hash_last',
                               rendered_image)
    def testSingleLines(self):
        source = QgsVectorLayer(os.path.join(TEST_DATA_DIR, 'lines_touching.shp'))
        self.assertTrue(source.isValid())
        map_settings = QgsMapSettings()
        map_settings.setExtent(source.extent().buffered(2))
        map_settings.setDestinationCrs(source.crs())
        map_settings.setLayers([source])

        layer = QgsSimpleLineSymbolLayer()
        layer.setColor(QColor(0, 0, 0))
        layer.setWidth(1)
        symbol = QgsLineSymbol([layer])

        layer2 = QgsMarkerLineSymbolLayer()
        layer2.setPlacement(QgsTemplatedLineSymbolLayerBase.FirstVertex)
        marker = QgsMarkerSymbol.createSimple({'size': '4', 'color': '255,0,0', 'outline_style': 'no'})
        layer2.setSubSymbol(marker)
        symbol.appendSymbolLayer(layer2)

        sub_renderer = QgsSingleSymbolRenderer(symbol)
        source.setRenderer(QgsMergedFeatureRenderer(sub_renderer))

        self.assertTrue(self.imageCheck('lines_single_subrenderer', 'lines_single_subrenderer', map_settings))
    def testPointNumInterval(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        hash_line = QgsHashedLineSymbolLayer(True)
        hash_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        hash_line.setInterval(6)
        simple_line = QgsSimpleLineSymbolLayer()
        simple_line.setColor(QColor(0, 255, 0))
        simple_line.setWidth(1)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, simple_line)
        hash_line.setSubSymbol(line_symbol)
        hash_line.setHashLength(10)

        s.appendSymbolLayer(hash_line.clone())

        s.symbolLayer(0).setDataDefinedProperty(
            QgsSymbolLayer.PropertyLineDistance,
            QgsProperty.fromExpression("@geometry_point_num * 2"))

        g = QgsGeometry.fromWkt('LineString(0 0, 10 10, 10 0)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('line_dd_size', 'line_dd_size', rendered_image)
Example #27
0
    def setTreeStyle(self, layer):
        # get unique values
        field = 'ArcType'
        fni = layer.fields().indexFromName(field)
        unique_values = layer.dataProvider().uniqueValues(fni)

        # define categories
        categories = []
        for unique_value in unique_values:
            # initialize the default symbol for this geometry type
            symbol = QgsSymbol.defaultSymbol(layer.geometryType())

            # configure a symbol layer
            symbol_layer = None
            if layer.geometryType() == 0:  # Point
                layer_style = dict()
                layer_style['color'] = '%d, %d, %d' % (randrange(
                    0, 256), randrange(0, 256), randrange(0, 256))
                layer_style['size'] = str(2)
                symbol_layer = QgsSimpleMarkerSymbolLayer.create(layer_style)
            else:
                symbol = QgsLineSymbol().createSimple({})
                symbol.deleteSymbolLayer(0)
                # Line
                lineSymbol = QgsSimpleLineSymbolLayer()
                lineSymbol.setWidthUnit(2)  # Pixels
                lineSymbol.setWidth(3)
                lineSymbol.setColor(QColor(178, 47, 60))
                if "Branch" in unique_value:
                    lineSymbol.setColor(QColor(22, 139, 251))
                else:
                    lineSymbol.setPenStyle(3)
                    lineSymbol.setWidth(1.5)
                symbol.appendSymbolLayer(lineSymbol)

            # replace default symbol layer with the configured one
            if symbol_layer is not None:
                symbol.changeSymbolLayer(0, symbol_layer)

            # create renderer object
            category = QgsRendererCategory(unique_value, symbol,
                                           str(unique_value))
            # entry for the list of category items
            categories.append(category)

        # create renderer object
        renderer = QgsCategorizedSymbolRenderer(field, categories)

        # assign the created renderer to the layer
        if renderer is not None:
            layer.setRenderer(renderer)
Example #28
0
    def make_flow_sym_renderer(self, layer, field_name, ranges_colors=None):

        feats = layer.getFeatures()

        min_val = sys.float_info.max
        max_val = -min_val

        # Find values range
        for feat in feats:
            attr = feat.attribute(field_name)
            val = float(attr)
            if val < min_val:
                min_val = val
            if val > max_val:
                max_val = val

        # Define colors
        if ranges_colors is None:
            ranges_colors = []
            colors = [
                QColor(0, 255, 0),
                QColor(128, 255, 0),
                QColor(255, 255, 0),
                QColor(255, 128, 0),
                QColor(255, 0, 0)]

            intv_nr = len(colors)
            intv = (max_val - min_val) / intv_nr
            for c in range(intv_nr):
                vrange = [min_val + intv * c, min_val + intv * (c + 1)]

                if c == len(colors) - 1:
                    vrange[1] = max_val

                ranges_colors.append([vrange, colors[c]])

        range_list = []
        for range_col in ranges_colors:
            r_min = range_col[0][0]
            r_max = range_col[0][1]
            title = str(r_min) + ' - ' + str(r_max)
            range_list.append(symbology_from_range(layer, r_min, r_max, range_col[1], title))

        renderer = QgsGraduatedSymbolRenderer(field_name, range_list)

        # Line
        symbol = QgsLineSymbol().createSimple({})
        symbol.deleteSymbolLayer(0)
        line_sym_lay = QgsSimpleLineSymbolLayer()
        line_sym_lay.setWidth(0.2)
        symbol.appendSymbolLayer(line_sym_lay)

        # Define arrows for flow and velocities
        if u'Link flow' in layer.name() in layer.name():
            self.marker_sym = QgsMarkerSymbol.createSimple({'name': 'triangle', 'color': 'black'})
            data_def_angle = QgsProperty()
            data_def_angle_exp =\
                'case ' \
                    'when  "' + field_name + '"  >= 0 ' \
                        'then degrees(azimuth( start_point( $geometry), end_point($geometry))) ' \
                    'else ' \
                        'case ' \
                            'when degrees(azimuth( start_point( $geometry), end_point($geometry)))  < 180 ' \
                                'then degrees(azimuth( start_point( $geometry), end_point($geometry))) + 180 ' \
                            'else ' \
                                'degrees(azimuth( start_point( $geometry), end_point($geometry))) - 180 ' \
                        'end ' \
                'end'
            data_def_angle.setExpressionString(data_def_angle_exp)
            data_def_angle.setActive(True)
            self.marker_sym.setDataDefinedAngle(data_def_angle)

            # Size: 0 if attribute = 0
            data_def_size = QgsProperty()
            data_def_size_exp =\
                'case ' \
                    'when "' + field_name + '" = 0 ' \
                        'then 0 ' \
                    'else ' \
                        '2 ' \
                'end'
            data_def_size.setExpressionString(data_def_size_exp)
            data_def_size.setActive(True)
            self.marker_sym.setDataDefinedSize(data_def_size)


            marker_sym_lay = QgsMarkerLineSymbolLayer()
            marker_sym_lay.setColor(QColor(0, 0, 0))
            marker_sym_lay.setFillColor(QColor(0, 0, 0))
            marker_sym_lay.setPlacement(QgsMarkerLineSymbolLayer.CentralPoint)
            marker_sym_lay.setRotateMarker(False)
            marker_sym_lay.setSubSymbol(self.marker_sym)

            self.marker_sym.appendSymbolLayer(marker_sym_lay)

            symbol.appendSymbolLayer(marker_sym_lay)

        # renderer.setSourceSymbol(symbol)
        renderer.updateSymbols(symbol)

        return renderer
Example #29
0
File: qgis.py Project: zyxgis/slyr
def append_SimpleLineSymbolLayer(symbol, layer, context: Context):
    """
    Appends a SimpleLineSymbolLayer to a symbol
    """
    color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleLineSymbolLayer(color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)
    out.setWidth(context.convert_size(max(
        0, layer.width)))  # sometimes lines have negative width?
    out.setWidthUnit(context.units)
    out.setPenStyle(symbol_pen_to_qpenstyle(layer.line_type))

    # better matching of null stroke color to QGIS symbology
    if out.color().alpha() == 0:
        out.setPenStyle(Qt.NoPen)

    symbol.appendSymbolLayer(out)
Example #30
0
    def testCondenseFillAndOutline(self):
        """
        Test QgsSymbolLayerUtils.condenseFillAndOutline
        """
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            None, None))

        # not simple fill or line
        self.assertFalse(
            QgsSymbolLayerUtils.condenseFillAndOutline(
                QgsShapeburstFillSymbolLayer(), QgsSimpleLineSymbolLayer()))
        self.assertFalse(
            QgsSymbolLayerUtils.condenseFillAndOutline(
                QgsSimpleFillSymbolLayer(), QgsMarkerLineSymbolLayer()))

        # simple fill/line
        fill = QgsSimpleFillSymbolLayer()
        line = QgsSimpleLineSymbolLayer()

        # set incompatible settings on outline
        line.setUseCustomDashPattern(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDashPatternOffset(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setAlignDashPattern(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTweakDashPatternOnCorners(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTrimDistanceStart(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTrimDistanceEnd(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDrawInsidePolygon(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setRingFilter(QgsSimpleLineSymbolLayer.ExteriorRingOnly)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setOffset(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDataDefinedProperty(QgsSymbolLayer.PropertyTrimEnd,
                                    QgsProperty.fromValue(4))
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        # compatible!
        line = QgsSimpleLineSymbolLayer()
        line.setColor(QColor(255, 0, 0))
        line.setWidth(1.2)
        line.setWidthUnit(QgsUnitTypes.RenderPoints)
        line.setWidthMapUnitScale(QgsMapUnitScale(1, 2))
        line.setPenJoinStyle(Qt.MiterJoin)
        line.setPenStyle(Qt.DashDotDotLine)
        self.assertTrue(QgsSymbolLayerUtils.condenseFillAndOutline(fill, line))

        self.assertEqual(fill.strokeColor(), QColor(255, 0, 0))
        self.assertEqual(fill.strokeWidth(), 1.2)
        self.assertEqual(fill.strokeWidthUnit(), QgsUnitTypes.RenderPoints)
        self.assertEqual(fill.strokeWidthMapUnitScale(), QgsMapUnitScale(1, 2))
        self.assertEqual(fill.penJoinStyle(), Qt.MiterJoin)
        self.assertEqual(fill.strokeStyle(), Qt.DashDotDotLine)
Example #31
0
def append_SimpleLineSymbolLayer(symbol, layer):
    """
    Appends a SimpleLineSymbolLayer to a symbol
    """
    color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleLineSymbolLayer(color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)
    out.setWidth(layer.width)
    out.setWidthUnit(QgsUnitTypes.RenderPoints)
    out.setPenStyle(symbol_pen_to_qpenstyle(layer.line_type))
    # out.setPenJoinStyle(symbol_pen_to_qpenjoinstyle(layer.join))
    # better matching of null stroke color to QGIS symbology
    if out.color().alpha() == 0:
        out.setPenStyle(Qt.NoPen)

    # todo - change to new symbol layer if outline offset set
    symbol.appendSymbolLayer(out)
Example #32
0
File: qgis.py Project: zyxgis/slyr
def append_CartographicLineSymbolLayer(symbol,
                                       layer: CartographicLineSymbolLayer,
                                       context: Context):
    """
    Appends a CartographicLineSymbolLayer to a symbol
    """
    color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleLineSymbolLayer(color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)
    out.setWidth(context.convert_size(max(
        0, layer.width)))  # sometimes lines have negative width?
    out.setWidthUnit(context.units)
    out.setPenJoinStyle(symbol_pen_to_qpenjoinstyle(layer.join))
    out.setPenCapStyle(symbol_pen_to_qpencapstyle(layer.cap))
    if layer.template is not None:
        apply_template_to_LineSymbolLayer_custom_dash(layer.template, out,
                                                      context)

    # better matching of null stroke color to QGIS symbology
    if out.color().alpha() == 0:
        out.setPenStyle(Qt.NoPen)

    out.setOffset(context.convert_size(layer.offset))
    out.setOffsetUnit(context.units)

    symbol.appendSymbolLayer(out)

    if layer.decoration is not None:
        append_Decorations(symbol, layer.decoration, context)
Example #33
0
    def setStyle(self, layer, name):
        if name == "":
            return
        stylePath = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                 "layerStyles")

        # user style
        qmlPath = os.path.join(stylePath, name + "_user.qml")
        if os.path.exists(qmlPath):
            layer.loadNamedStyle(qmlPath)
            return

        # default style
        qmlPath = os.path.join(stylePath, name + ".qml.bak")
        if os.path.exists(qmlPath):
            layer.loadNamedStyle(qmlPath)
        svgPath = os.path.join(stylePath, name + ".svg")
        if os.path.exists(svgPath):
            if layer.geometryType() == 0:  # Point
                svg_style = dict()
                svg_style['name'] = svgPath
                svg_style['size'] = str(7)
                if name == "demands":
                    svg_style['fill'] = '#9a1313'
                symbol_layer = QgsSvgMarkerSymbolLayer.create(svg_style)
                symbol = QgsSymbol.defaultSymbol(layer.geometryType())
                symbol.changeSymbolLayer(0, symbol_layer)
                renderer = QgsSingleSymbolRenderer(symbol)
            else:  # Line
                symbol = QgsLineSymbol().createSimple({})
                symbol.deleteSymbolLayer(0)
                # Line
                lineSymbol = QgsSimpleLineSymbolLayer()
                lineSymbol.setWidthUnit(2)  # Pixels
                lineSymbol.setWidth(1.5)
                if name == "pipes":
                    lineSymbol.setColor(QColor("#0f1291"))
                symbol.appendSymbolLayer(lineSymbol)
                # Symbol
                marker = QgsMarkerSymbol.createSimple({})
                marker.deleteSymbolLayer(0)
                svg_props = dict()
                svg_props['name'] = svgPath
                size = 5
                if name == "pipes":
                    size = 0
                svg_props['size'] = str(size)
                svg_props['offset'] = '-0.5,-0.5'
                svg_props['offset_unit'] = 'Pixel'
                markerSymbol = QgsSvgMarkerSymbolLayer.create(svg_props)
                marker.appendSymbolLayer(markerSymbol)
                # Final Symbol
                finalMarker = QgsMarkerLineSymbolLayer()
                finalMarker.setSubSymbol(marker)
                finalMarker.setPlacement(QgsMarkerLineSymbolLayer.CentralPoint)
                symbol.appendSymbolLayer(finalMarker)
                if name == "pipes":
                    prop = QgsProperty()
                    prop.setExpressionString(
                        "if(IniStatus is NULL, 0,if(IniStatus !='CV', 0,5))")
                    symbol.symbolLayer(1).setDataDefinedProperty(
                        9, prop)  # 9 = PropertyWidth
                renderer = QgsSingleSymbolRenderer(symbol)

            layer.setRenderer(renderer)
Example #34
0
    def editNetworkLayer(self, progressBar, layerName, scenariosExpression,
                         networkExpression, variable, level, projectPath,
                         group, networkLinkShapePath, method, layerId,
                         expressionNetworkText, color):
        """
            @summary: Get operators dictionary
            @param layerName: Layer name
            @type layerName: String
            @param scenariosExpression: Scenarios expression
            @type scenariosExpression: Stack object
            @param networkExpression: Network expression
            @type networkExpression: Stack object
            @param variable: Variable to evaluate
            @type variable: String
            @param level: Level to evaluate (Total, Routes, Operators)
            @type level: Level object
            @param projectPath: Project path
            @type projectPath: String
            @param group: Project group
            @type group: Layer group
            @param networkLinkShapePath: Network link shape path
            @type networkLinkShapePath: String
            @return: Result of the layer creation
        """

        if scenariosExpression is None:
            QMessageBox.warning(None, "Network expression",
                                "There is not scenarios information.")
            print("There is not scenarios information.")
            return False

        registry = QgsProject.instance()
        layersCount = len(registry.mapLayers())
        result, resultData, minValue, maxValue = self.network_data_access.create_network_memory(
            layerName, scenariosExpression, networkExpression, variable, level,
            projectPath)
        progressBar.setValue(15)

        if result:
            # Source shape, name of the new shape, providerLib
            layer = QgsVectorLayer(networkLinkShapePath,
                                   layerName + "_network", 'ogr')
            epsg = layer.crs().postgisSrid()
            intMethod = 0 if method == "Color" else 1
            rowCounter = len(resultData)

            if not layer.isValid():
                return False

            feats = [feat for feat in layer.getFeatures()]

            # Create a vector layer with data on Memory
            memoryLayer = registry.mapLayer(layerId)

            memory_data = memoryLayer.dataProvider()
            joinedFieldName = "Result"
            shpField = "Id"
            attr = layer.dataProvider().fields().toList()
            attr += [QgsField(joinedFieldName, QVariant.Double)]
            progressBar.setValue(25)

            memory_data.addAttributes(attr)
            memory_data.addFeatures(feats)

            num = 30
            progressBar.setValue(num)
            progressInterval = 70 / len(resultData)

            memoryLayer.startEditing()
            for rowItem in np.nditer(resultData):
                value = 0
                num += progressInterval
                progressBar.setValue(num)

                it = memoryLayer.getFeatures("LINKID  = '{0}'".format(
                    str(rowItem['Id']).replace("b", "").replace("'", "")))
                for id_feature in it:
                    memoryLayer.changeAttributeValue(
                        id_feature.id(),
                        memory_data.fieldNameIndex(joinedFieldName),
                        QVariant(round(float(rowItem['Result']), 2)))

            memoryLayer.commitChanges()

            myStyle = QgsStyle().defaultStyle()
            defaultColorRampNames = myStyle.colorRampNames()
            ramp = myStyle.colorRamp(defaultColorRampNames[0])
            ranges = []
            nCats = ramp.count()
            rng = maxValue - minValue
            nCats = 8
            scale = QgsMapUnitScale(minValue, maxValue)

            if method == "Color":
                color1 = list(
                    map(lambda x: int(x), color['color1'].split(",")[0:3]))
                color2 = list(
                    map(lambda x: int(x), color['color2'].split(",")[0:3]))
                interpolatedColors = HP.linear_gradient(color1, color2, nCats)

            for i in range(0, nCats):
                v0 = minValue + rng / float(nCats) * i
                v1 = minValue + rng / float(nCats) * (i + 1)
                if method == "Color":
                    line = QgsSimpleLineSymbolLayer(
                        QColor(interpolatedColors['r'][i],
                               interpolatedColors['g'][i],
                               interpolatedColors['b'][i]))
                    line.setOffsetUnit(2)
                    line.setOffset(2)
                    line.setWidth(0.8)
                    symbol = QgsLineSymbol()
                    symbol.changeSymbolLayer(0, line)
                    myRange = QgsRendererRange(v0, v1, symbol, "")

                elif method == "Size":
                    qcolor = QColor()
                    qcolor.setRgb(color)
                    line = QgsSimpleLineSymbolLayer(qcolor)
                    line.setOffsetUnit(2)
                    line.setOffset(0.7)
                    # Symbol
                    # symbolLine = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.ArrowHead)
                    # Mark line
                    # markLine = QgsMarkerLineSymbolLayer()
                    # markLine.setPlacement(4)
                    symbolo = QgsLineSymbol()
                    symbolo.changeSymbolLayer(0, line)
                    # symbolo.appendSymbolLayer(line)
                    myRange = QgsRendererRange(v0, v1, symbolo, "")
                ranges.append(myRange)

            # The first parameter refers to the name of the field that contains the calculated value (expression)
            modeRender = QgsGraduatedSymbolRenderer.Mode(2)
            renderer = QgsGraduatedSymbolRenderer(joinedFieldName, ranges)
            renderer.setMode(modeRender)
            renderer.setGraduatedMethod(intMethod)

            if method == "Size":
                renderer.setSymbolSizes(0.200000, 2.60000)

            renderer.setSourceColorRamp(ramp)
            memoryLayer.setRenderer(renderer)

            typeLayer = "network"
            fieldName = "LINKID"
            networkExpressionText = str(scenariosExpression)

            # Create XML File ".qtranus" with the parameters of the executions
            if FileMXML.if_exist_xml_layers(projectPath):
                if FileMXML.if_exist_layer(projectPath, memoryLayer.id()):
                    FileMXML.update_xml_file(memoryLayer.name(),
                                             memoryLayer.id(),
                                             scenariosExpression, variable,
                                             networkExpression, projectPath,
                                             expressionNetworkText, method,
                                             level, color)
                else:
                    FileMXML.add_layer_xml_file(memoryLayer.name(),
                                                memoryLayer.id(),
                                                scenariosExpression, variable,
                                                networkExpression, projectPath,
                                                expressionNetworkText,
                                                shpField, typeLayer, method,
                                                level, color)
            else:
                FileMXML.create_xml_file(memoryLayer.name(), memoryLayer.id(),
                                         scenariosExpression, variable,
                                         networkExpression, projectPath,
                                         expressionNetworkText, shpField,
                                         typeLayer, method, level, color)

            #group.insertLayer((layersCount+1), memoryLayer)
            progressBar.setValue(100)

        return True
Example #35
0
def append_CartographicLineSymbolLayer(symbol, layer):
    """
    Appends a CartographicLineSymbolLayer to a symbol
    """
    color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleLineSymbolLayer(color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)
    out.setWidth(points_to_mm(layer.width))
    out.setPenJoinStyle(symbol_pen_to_qpenjoinstyle(layer.join))
    out.setPenCapStyle(symbol_pen_to_qpencapstyle(layer.cap))
    if layer.pattern_parts:
        interval = layer.pattern_interval

        dash_vector = []
        for part in layer.pattern_parts:
            dash_vector.append(points_to_mm(part[0] * interval))
            dash_vector.append(points_to_mm(part[1] * interval))

        out.setCustomDashVector(dash_vector)
        out.setUseCustomDashPattern(True)

    # better matching of null stroke color to QGIS symbology
    if out.color().alpha() == 0:
        out.setPenStyle(Qt.NoPen)

    if layer.marker_positions or layer.marker:
        raise NotImplementedException(
            'Cartographic line start/end markers are not yet supported')

    # todo - change to new symbol layer if outline offset set
    symbol.appendSymbolLayer(out)
Example #36
0
def append_CartographicLineSymbolLayer(symbol, layer: CartographicLineSymbolLayer):
    """
    Appends a CartographicLineSymbolLayer to a symbol
    """
    color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleLineSymbolLayer(color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)
    out.setWidth(layer.width)
    out.setWidthUnit(QgsUnitTypes.RenderPoints)
    out.setPenJoinStyle(symbol_pen_to_qpenjoinstyle(layer.join))
    out.setPenCapStyle(symbol_pen_to_qpencapstyle(layer.cap))
    if layer.template is not None:
        apply_template_to_LineSymbolLayer_custom_dash(layer.template, out)

    # better matching of null stroke color to QGIS symbology
    if out.color().alpha() == 0:
        out.setPenStyle(Qt.NoPen)

    out.setOffset(layer.offset)
    out.setOffsetUnit(QgsUnitTypes.RenderPoints)

    symbol.appendSymbolLayer(out)

    if layer.decoration is not None:
        append_Decorations(symbol, layer.decoration)