def testPartNum(self):
        # test geometry_part_num variable
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        sym_layer = QgsGeometryGeneratorSymbolLayer.create({'geometryModifier': 'segments_to_lines($geometry)'})
        sym_layer.setSymbolType(QgsSymbol.Line)
        s.appendSymbolLayer(sym_layer)

        marker_line = QgsMarkerLineSymbolLayer(False)
        marker_line.setPlacement(QgsMarkerLineSymbolLayer.FirstVertex)
        f = QgsFontUtils.getStandardTestFont('Bold', 24)
        marker = QgsFontMarkerSymbolLayer(f.family(), 'x', 24, QColor(255, 255, 0))
        marker.setDataDefinedProperty(QgsSymbolLayer.PropertyCharacter, QgsProperty.fromExpression('@geometry_part_num'))
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)
        marker_line.setAverageAngleLength(0)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, marker_line)
        sym_layer.setSubSymbol(line_symbol)

        # rendering test
        g = QgsGeometry.fromWkt('LineString(0 0, 10 0, 10 10, 0 10)')
        rendered_image = self.renderGeometry(s, g, buffer=4)
        assert self.imageCheck('part_num_variable', 'part_num_variable', rendered_image)

        marker.setDataDefinedProperty(QgsSymbolLayer.PropertyCharacter,
                                      QgsProperty.fromExpression('@geometry_part_count'))

        # rendering test
        g = QgsGeometry.fromWkt('LineString(0 0, 10 0, 10 10, 0 10)')
        rendered_image = self.renderGeometry(s, g, buffer=4)
        assert self.imageCheck('part_count_variable', 'part_count_variable', rendered_image)
    def testWidth(self):
        ms = QgsMapSettings()
        extent = QgsRectangle(100, 200, 100, 200)
        ms.setExtent(extent)
        ms.setOutputSize(QSize(400, 400))
        context = QgsRenderContext.fromMapSettings(ms)
        context.setScaleFactor(96 / 25.4)  # 96 DPI
        ms.setExtent(QgsRectangle(100, 150, 100, 150))
        ms.setOutputDpi(ms.outputDpi() * 2)
        context2 = QgsRenderContext.fromMapSettings(ms)
        context2.setScaleFactor(300 / 25.4)

        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)

        marker_line = QgsMarkerLineSymbolLayer(True)
        marker_line.setPlacement(QgsMarkerLineSymbolLayer.FirstVertex)
        marker = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayer.Triangle, 10)
        marker.setColor(QColor(255, 0, 0))
        marker.setStrokeStyle(Qt.NoPen)
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)

        self.assertEqual(marker_line.width(), 10)
        self.assertAlmostEqual(marker_line.width(context), 37.795275590551185, 3)
        self.assertAlmostEqual(marker_line.width(context2), 118.11023622047244, 3)

        marker_line.subSymbol().setSizeUnit(QgsUnitTypes.RenderPixels)
        self.assertAlmostEqual(marker_line.width(context), 10.0, 3)
        self.assertAlmostEqual(marker_line.width(context2), 10.0, 3)
示例#3
0
    def testRenderMarkerLayerDataDefined(self):
        """ test that rendering a marker symbol with data defined enabled layer works"""

        points_shp = os.path.join(TEST_DATA_DIR, 'points.shp')
        points_layer = QgsVectorLayer(points_shp, 'Points', 'ogr')
        QgsProject.instance().addMapLayer(points_layer)

        layer = QgsSimpleMarkerSymbolLayer()
        layer.setDataDefinedProperty(QgsSymbolLayer.PropertyLayerEnabled, QgsProperty.fromExpression("Class='Biplane'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setSize(5)
        layer.setStrokeStyle(Qt.NoPen)

        symbol = QgsMarkerSymbol()
        symbol.changeSymbolLayer(0, layer)
        points_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

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

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_markerlayer_ddenabled')
        self.assertTrue(renderchecker.runTest('markerlayer_ddenabled'))
        QgsProject.instance().removeMapLayer(points_layer)
    def testConvert(self):
        """ test renderer conversion """

        # same type, should clone
        r = QgsPointClusterRenderer()
        self._setProperties(r)
        c = QgsPointClusterRenderer.convertFromRenderer(r)
        self._checkProperties(c)

        # test conversion from displacement renderer
        r = QgsPointDisplacementRenderer()
        r.setTolerance(5)
        r.setToleranceUnit(QgsUnitTypes.RenderMapUnits)
        r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15))
        m = QgsMarkerSymbol()
        m.setColor(QColor(0, 255, 0))
        r.setCenterSymbol(m)
        sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'})
        renderer = QgsSingleSymbolRenderer(sym1)
        r.setEmbeddedRenderer(renderer)

        # want to keep as many settings as possible when converting between cluster and displacement renderer
        d = QgsPointClusterRenderer.convertFromRenderer(r)
        self.assertEqual(d.tolerance(), 5)
        self.assertEqual(d.toleranceUnit(), QgsUnitTypes.RenderMapUnits)
        self.assertEqual(d.toleranceMapUnitScale(), QgsMapUnitScale(5, 15))
        self.assertEqual(d.clusterSymbol().color(), QColor(0, 255, 0))
        self.assertEqual(d.embeddedRenderer().symbol().color().name(), '#fdbf6f')
示例#5
0
    def legend_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)", "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRenderer("attr", [QgsRendererCategory(1, QgsMarkerSymbol.createSimple({"color": "255,0,0"}), "red"),
                                                  QgsRendererCategory(2, QgsMarkerSymbol.createSimple({"color": "0,0,255"}), "blue")])
        ptLayer.setRenderer(r)

        QgsProject.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.layers
        layers = [ptLayer] + layers
        self.mAtlasMap.setLayers(layers)
        self.mOverview.setLayers(layers)

        # add a legend
        legend = QgsComposerLegend(self.mComposition)
        legend.moveBy(200, 100)
        # sets the legend filter parameter
        legend.setComposerMap(self.mAtlasMap)
        legend.setLegendFilterOutAtlas(True)
        self.mComposition.addComposerLegend(legend)

        self.mAtlas.beginRender()

        self.mAtlas.prepareForFeature(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsCompositionChecker('atlas_legend', self.mComposition)
        myTestResult, myMessage = checker.testComposition()
        assert myTestResult

        self.mAtlas.endRender()

        # restore state
        self.mAtlasMap.setLayers([layers[1]])
        self.mComposition.removeComposerItem(legend)
        QgsProject.instance().removeMapLayer(ptLayer.id())
 def _create_categorized_renderer(self):
     cat_renderer = QgsCategorizedSymbolRenderer(attrName='Class')
     sym1 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '6', 'outline_style': 'no'})
     cat1 = QgsRendererCategory('Biplane', sym1, 'Big')
     cat_renderer.addCategory(cat1)
     sym2 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '3', 'outline_style': 'no'})
     cat2 = QgsRendererCategory(['B52', 'Jet'], sym2, 'Smaller')
     cat_renderer.addCategory(cat2)
     return cat_renderer
示例#7
0
    def testRenderMarkerLayerDisabled(self):
        """ test that rendering a marker symbol with disabled layer works"""
        layer = QgsSimpleMarkerSymbolLayer()
        layer.setEnabled(False)

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

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

        geom = QgsGeometry.fromWkt('Point (1 2)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = QgsRectangle(0, 0, 4, 4)

        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 _setProperties(self, r):
     """ set properties for a renderer for testing with _checkProperties"""
     r.setTolerance(5)
     r.setToleranceUnit(QgsUnitTypes.RenderMapUnits)
     r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15))
     m = QgsMarkerSymbol()
     m.setColor(QColor(0, 255, 0))
     r.setClusterSymbol(m)
     sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'})
     renderer = QgsSingleSymbolRenderer(sym1)
     r.setEmbeddedRenderer(renderer)
def createMarkerSymbol():
    symbol = QgsMarkerSymbol.createSimple({
        "color": "100,150,50",
        "name": "square",
        "size": "3.0"
    })
    return symbol
    def setUp(self):
        self.iface = get_iface()

        polys_shp = os.path.join(TEST_DATA_DIR, "polys.shp")
        points_shp = os.path.join(TEST_DATA_DIR, "points.shp")
        lines_shp = os.path.join(TEST_DATA_DIR, "lines.shp")
        self.polys_layer = QgsVectorLayer(polys_shp, "Polygons", "ogr")
        self.points_layer = QgsVectorLayer(points_shp, "Points", "ogr")
        self.lines_layer = QgsVectorLayer(lines_shp, "Lines", "ogr")
        QgsMapLayerRegistry.instance().addMapLayer(self.polys_layer)
        QgsMapLayerRegistry.instance().addMapLayer(self.lines_layer)
        QgsMapLayerRegistry.instance().addMapLayer(self.points_layer)

        # Create style
        sym1 = QgsFillSymbol.createSimple({"color": "#fdbf6f"})
        sym2 = QgsLineSymbol.createSimple({"color": "#fdbf6f"})
        sym3 = QgsMarkerSymbol.createSimple({"color": "#fdbf6f"})

        self.polys_layer.setRenderer(QgsSingleSymbolRenderer(sym1))
        self.lines_layer.setRenderer(QgsSingleSymbolRenderer(sym2))
        self.points_layer.setRenderer(QgsSingleSymbolRenderer(sym3))

        self.mapsettings = self.iface.mapCanvas().mapSettings()
        self.mapsettings.setOutputSize(QSize(400, 400))
        self.mapsettings.setOutputDpi(96)
        self.mapsettings.setExtent(QgsRectangle(-133, 22, -70, 52))
    def setUp(self):
        self.iface = get_iface()

        polys_shp = os.path.join(TEST_DATA_DIR, 'polys.shp')
        points_shp = os.path.join(TEST_DATA_DIR, 'points.shp')
        lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp')
        self.polys_layer = QgsVectorLayer(polys_shp, 'Polygons', 'ogr')
        self.points_layer = QgsVectorLayer(points_shp, 'Points', 'ogr')
        self.lines_layer = QgsVectorLayer(lines_shp, 'Lines', 'ogr')
        QgsProject.instance().addMapLayer(self.polys_layer)
        QgsProject.instance().addMapLayer(self.lines_layer)
        QgsProject.instance().addMapLayer(self.points_layer)

        # Create style
        sym1 = QgsFillSymbol.createSimple({'color': '#fdbf6f', 'outline_color': 'black'})
        sym2 = QgsLineSymbol.createSimple({'color': '#fdbf6f'})
        sym3 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f', 'outline_color': 'black'})

        self.polys_layer.setRenderer(QgsSingleSymbolRenderer(sym1))
        self.lines_layer.setRenderer(QgsSingleSymbolRenderer(sym2))
        self.points_layer.setRenderer(QgsSingleSymbolRenderer(sym3))

        self.mapsettings = self.iface.mapCanvas().mapSettings()
        self.mapsettings.setOutputSize(QSize(400, 400))
        self.mapsettings.setOutputDpi(96)
        self.mapsettings.setExtent(QgsRectangle(-133, 22, -70, 52))
    def testInitialSizeSymbolMapUnits(self):
        """Test initial size of legend with a symbol size in map units"""

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
        QgsProject.instance().addMapLayers([point_layer])

        marker_symbol = QgsMarkerSymbol.createSimple({'color': '#ff0000', 'outline_style': 'no', 'size': '5', 'size_unit': 'MapUnit'})

        point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))

        s = QgsMapSettings()
        s.setLayers([point_layer])
        layout = QgsLayout(QgsProject.instance())
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.setTitle("Legend")
        legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        layout.addLayoutItem(legend)
        legend.setLinkedMap(map)

        checker = QgsLayoutChecker(
            'composer_legend_mapunits', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        # resize with non-top-left reference point
        legend.setResizeToContents(False)
        legend.setReferencePoint(QgsLayoutItem.LowerRight)
        legend.attemptMove(QgsLayoutPoint(120, 90))
        legend.attemptResize(QgsLayoutSize(50, 60))

        self.assertEqual(legend.positionWithUnits().x(), 120.0)
        self.assertEqual(legend.positionWithUnits().y(), 90.0)
        self.assertAlmostEqual(legend.pos().x(), 70, -1)
        self.assertAlmostEqual(legend.pos().y(), 30, -1)

        legend.setResizeToContents(True)
        legend.updateLegend()
        self.assertEqual(legend.positionWithUnits().x(), 120.0)
        self.assertEqual(legend.positionWithUnits().y(), 90.0)
        self.assertAlmostEqual(legend.pos().x(), 91, -1)
        self.assertAlmostEqual(legend.pos().y(), 71, -1)

        QgsProject.instance().removeMapLayers([point_layer.id()])
    def testRingFilter(self):
        # test filtering rings during rendering
        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)

        marker_line = QgsMarkerLineSymbolLayer(True)
        marker_line.setPlacement(QgsMarkerLineSymbolLayer.FirstVertex)
        marker = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayer.Triangle, 4)
        marker.setColor(QColor(255, 0, 0))
        marker.setStrokeStyle(Qt.NoPen)
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)

        s.appendSymbolLayer(marker_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(
            QgsMarkerLineSymbolLayer())
        s3.symbolLayer(0).setRingFilter(QgsLineSymbolLayer.ExteriorRingOnly)
        s3.symbolLayer(0).setAverageAngleLength(0)

        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('markerline_exterioronly', 'markerline_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('markerline_interioronly', 'markerline_interioronly', rendered_image)
    def setUp(self):
        myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp')
        self.layer = QgsVectorLayer(myShpFile, 'Points', 'ogr')
        QgsProject.instance().addMapLayer(self.layer)

        self.renderer = QgsPointClusterRenderer()
        sym1 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '3', 'outline_style': 'no'})
        renderer = QgsSingleSymbolRenderer(sym1)
        self.renderer.setEmbeddedRenderer(renderer)
        self.renderer.setClusterSymbol(QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'}))
        self.layer.setRenderer(self.renderer)

        rendered_layers = [self.layer]
        self.mapsettings = QgsMapSettings()
        self.mapsettings.setOutputSize(QSize(400, 400))
        self.mapsettings.setOutputDpi(96)
        self.mapsettings.setExtent(QgsRectangle(-123, 18, -70, 52))
        self.mapsettings.setLayers(rendered_layers)
示例#15
0
    def testForceRHR(self):
        # test forcing right hand rule during rendering

        s = QgsFillSymbol()
        s.deleteSymbolLayer(0)
        s.appendSymbolLayer(
            QgsSimpleFillSymbolLayer(color=QColor(255, 0, 0), strokeColor=QColor(0, 255, 0)))
        self.assertFalse(s.forceRHR())
        s.setForceRHR(True)
        self.assertTrue(s.forceRHR())
        s.setForceRHR(False)
        self.assertFalse(s.forceRHR())

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

        s2 = QgsSymbolLayerUtils.loadSymbol(element, context)
        self.assertTrue(s2.forceRHR())

        # rendering test
        s3 = QgsFillSymbol()
        s3.deleteSymbolLayer(0)
        s3.appendSymbolLayer(
            QgsSimpleFillSymbolLayer(color=QColor(255, 200, 200), strokeColor=QColor(0, 255, 0), strokeWidth=2))
        marker_line = QgsMarkerLineSymbolLayer(True)
        marker_line.setPlacement(QgsMarkerLineSymbolLayer.FirstVertex)
        marker = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayer.Triangle, 4)
        marker.setColor(QColor(255, 0, 0))
        marker.setStrokeStyle(Qt.NoPen)
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)
        s3.appendSymbolLayer(marker_line)

        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('force_rhr_off', 'polygon_forcerhr_off', rendered_image)

        s3.setForceRHR(True)
        rendered_image = self.renderGeometry(s3, g)
        assert self.imageCheck('force_rhr_on', 'polygon_forcerhr_on', rendered_image)
 def _setProperties(self, r):
     """ set properties for a renderer for testing with _checkProperties"""
     r.setLabelAttributeName('name')
     f = QgsFontUtils.getStandardTestFont('Bold Oblique', 14)
     r.setLabelFont(f)
     r.setMinimumLabelScale(50000)
     r.setLabelColor(QColor(255, 0, 0))
     r.setTolerance(5)
     r.setToleranceUnit(QgsUnitTypes.RenderMapUnits)
     r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15))
     r.setCircleWidth(15)
     r.setCircleColor(QColor(0, 255, 0))
     r.setCircleRadiusAddition(2.5)
     r.setPlacement(QgsPointDisplacementRenderer.ConcentricRings)
     m = QgsMarkerSymbol()
     m.setColor(QColor(0, 255, 0))
     r.setCenterSymbol(m)
     sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'})
     renderer = QgsSingleSymbolRenderer(sym1)
     r.setEmbeddedRenderer(renderer)
示例#17
0
    def testSetGetSymbol(self):
        button = QgsSymbolButton()
        symbol = QgsMarkerSymbol.createSimple({})
        symbol.setColor(QColor(255, 0, 0))

        signal_spy = QSignalSpy(button.changed)
        button.setSymbol(symbol)
        self.assertEqual(len(signal_spy), 1)

        r = button.symbol()
        self.assertEqual(r.color(), QColor(255, 0, 0))
    def setUp(self):
        myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp')
        self.layer = QgsVectorLayer(myShpFile, 'Points', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(self.layer)

        self.renderer = QgsPointDisplacementRenderer()
        sym1 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '3', 'outline_style': 'no'})
        renderer = QgsSingleSymbolRenderer(sym1)
        self.renderer.setEmbeddedRenderer(renderer)
        self.renderer.setCircleRadiusAddition(2)
        self.renderer.setCircleWidth(1)
        self.renderer.setCircleColor(QColor(0, 0, 0))
        self.renderer.setCenterSymbol(QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'}))
        self.layer.setRenderer(self.renderer)

        rendered_layers = [self.layer.id()]
        self.mapsettings = QgsMapSettings()
        self.mapsettings.setOutputSize(QSize(400, 400))
        self.mapsettings.setOutputDpi(96)
        self.mapsettings.setExtent(QgsRectangle(-123, 18, -70, 52))
        self.mapsettings.setLayers(rendered_layers)
    def testMarkerAverageAngleCenter(self):
        s = QgsLineSymbol()
        s.deleteSymbolLayer(0)

        marker_line = QgsMarkerLineSymbolLayer(True)
        marker_line.setPlacement(QgsTemplatedLineSymbolLayerBase.CentralPoint)
        marker = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayer.Triangle, 4)
        marker.setColor(QColor(255, 0, 0))
        marker.setStrokeStyle(Qt.NoPen)
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)
        marker_line.setAverageAngleLength(60)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, marker_line)

        s.appendSymbolLayer(marker_line.clone())

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

        marker_line = QgsMarkerLineSymbolLayer(True)
        marker_line.setPlacement(QgsTemplatedLineSymbolLayerBase.Interval)
        marker_line.setOffsetAlongLine(1000)
        marker_line.setIntervalUnit(QgsUnitTypes.RenderMapUnits)
        marker = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayer.Circle, 4)
        marker.setColor(QColor(255, 0, 0, 100))
        marker.setStrokeStyle(Qt.NoPen)
        marker_symbol = QgsMarkerSymbol()
        marker_symbol.changeSymbolLayer(0, marker)
        marker_line.setSubSymbol(marker_symbol)
        line_symbol = QgsLineSymbol()
        line_symbol.changeSymbolLayer(0, marker_line)

        s.appendSymbolLayer(marker_line.clone())

        g = QgsGeometry.fromWkt('LineString(0 0, 0 10, 10 10)')
        rendered_image = self.renderGeometry(s, g)
        assert self.imageCheck('markerline_none', 'markerline_none', rendered_image)
示例#21
0
 def testSymbolToFromMimeData(self):
     """
     Test converting symbols to and from mime data
     """
     symbol = QgsMarkerSymbol.createSimple({})
     symbol.setColor(QColor(255, 0, 255))
     self.assertFalse(QgsSymbolLayerUtils.symbolFromMimeData(None))
     self.assertFalse(QgsSymbolLayerUtils.symbolToMimeData(None))
     mime = QgsSymbolLayerUtils.symbolToMimeData(symbol)
     self.assertTrue(mime is not None)
     symbol2 = QgsSymbolLayerUtils.symbolFromMimeData(mime)
     self.assertTrue(symbol2 is not None)
     self.assertEqual(symbol2.color().name(), symbol.color().name())
    def testMarkLineUnitDefault(self):
        symbol = QgsMarkerLineSymbolLayer()
        symbol.setSubSymbol(QgsMarkerSymbol.createSimple({"color": "#ffffff", "size": "3"}))
        symbol.setInterval(5)
        symbol.setOffset(5)
        dom, root = self.symbolToSld(symbol)

        # print ("Mark line mm: \n" + dom.toString())

        # size of the mark
        self.assertStaticSize(root, "11")
        # gap and offset
        self.assertStaticGap(root, "18")
        self.assertStaticPerpendicularOffset(root, "18")
示例#23
0
    def testSettingSymbolType(self):
        button = QgsSymbolButton()
        button.setSymbolType(QgsSymbol.Marker)
        symbol = QgsMarkerSymbol.createSimple({})
        symbol.setColor(QColor(255, 0, 0))
        button.setSymbol(symbol)

        # if same symbol type, existing symbol should be kept
        button.setSymbolType(QgsSymbol.Marker)
        self.assertEqual(button.symbol(), symbol)

        # if setting different symbol type, symbol should be reset to new type
        button.setSymbolType(QgsSymbol.Fill)
        self.assertTrue(isinstance(button.symbol(), QgsFillSymbol))
    def testMarkLineUnitPixels(self):
        symbol = QgsMarkerLineSymbolLayer()
        symbol.setSubSymbol(QgsMarkerSymbol.createSimple({"color": "#ffffff", "size": "3"}))
        symbol.setInterval(5)
        symbol.setOffset(5)
        symbol.setOutputUnit(QgsUnitTypes.RenderPixels)
        dom, root = self.symbolToSld(symbol)

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

        # size of the mark
        self.assertStaticSize(root, "3")
        # gap and offset
        self.assertStaticGap(root, "5")
        self.assertStaticPerpendicularOffset(root, "5")
    def testRenderVariables(self):
        """ test rendering with expression variables in marker """
        self.layer.renderer().setTolerance(10)

        old_marker = self.layer.renderer().clusterSymbol().clone()

        new_marker = QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'})
        new_marker.symbolLayer(0).setDataDefinedProperty(QgsSymbolLayer.PropertyFillColor, QgsProperty.fromExpression('@cluster_color'))
        new_marker.symbolLayer(0).setDataDefinedProperty(QgsSymbolLayer.PropertySize, QgsProperty.fromExpression('@cluster_size*2'))
        self.layer.renderer().setClusterSymbol(new_marker)
        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(self.mapsettings)
        renderchecker.setControlPathPrefix('cluster_renderer')
        renderchecker.setControlName('expected_cluster_variables')
        result = renderchecker.runTest('expected_cluster_variables')
        self.layer.renderer().setClusterSymbol(old_marker)
        self.assertTrue(result)
 def test_point_ordered_symbol_bound_offset(self):
     # Test ordered placements for point using symbol bounds offset
     self.layer = TestQgsPalLabeling.loadFeatureLayer('point_ordered_placement')
     # Make a big symbol
     symbol = QgsMarkerSymbol.createSimple({'color': '31,120,180,255',
                                            'outline_color': '0,0,0,0',
                                            'outline_style': 'solid',
                                            'size': '10',
                                            'name': 'rectangle',
                                            'size_unit': 'MM'})
     renderer = QgsSingleSymbolRenderer(symbol)
     self.layer.setRenderer(renderer)
     self._TestMapSettings = self.cloneMapSettings(self._MapSettings)
     self.lyr.placement = QgsPalLayerSettings.OrderedPositionsAroundPoint
     self.lyr.dist = 2
     self.lyr.offsetType = QgsPalLayerSettings.FromSymbolBounds
     self.checkTest()
     self.removeMapLayer(self.layer)
     self.layer = None
示例#27
0
    def testInitialSizeSymbolMapUnits(self):
        """Test initial size of legend with a symbol size in map units"""

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
        QgsProject.instance().addMapLayers([point_layer])

        marker_symbol = QgsMarkerSymbol.createSimple({'color': '#ff0000', 'outline_style': 'no', 'size': '5', 'size_unit': 'MapUnit'})

        point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))

        s = QgsMapSettings()
        s.setLayers([point_layer])
        layout = QgsLayout(QgsProject.instance())
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        layout.addLayoutItem(legend)
        legend.setMap(map)

        checker = QgsLayoutChecker(
            'composer_legend_mapunits', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        QgsProject.instance().removeMapLayers([point_layer.id()])
示例#28
0
    def testInitialSizeSymbolMapUnits(self):
        """Test initial size of legend with a symbol size in map units"""

        point_path = os.path.join(TEST_DATA_DIR, "points.shp")
        point_layer = QgsVectorLayer(point_path, "points", "ogr")
        QgsProject.instance().addMapLayers([point_layer])

        marker_symbol = QgsMarkerSymbol.createSimple(
            {"color": "#ff0000", "outline_style": "no", "size": "5", "size_unit": "MapUnit"}
        )

        point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))

        s = QgsMapSettings()
        s.setLayers([point_layer])
        s.setCrsTransformEnabled(False)
        composition = QgsComposition(s, QgsProject.instance())
        composition.setPaperSize(297, 210)

        composer_map = QgsComposerMap(composition, 20, 20, 80, 80)
        composer_map.setFrameEnabled(True)
        composition.addComposerMap(composer_map)
        composer_map.setNewExtent(point_layer.extent())

        legend = QgsComposerLegend(composition)
        legend.setSceneRect(QRectF(120, 20, 80, 80))
        legend.setFrameEnabled(True)
        legend.setFrameOutlineWidth(2)
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle("")
        composition.addComposerLegend(legend)
        legend.setComposerMap(composer_map)

        checker = QgsCompositionChecker("composer_legend_mapunits", composition)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testComposition()
        self.assertTrue(result, message)

        QgsProject.instance().removeMapLayers([point_layer.id()])
示例#29
0
    def testConvertFromCategorisedRenderer(self):
        # Test converting categorised renderer to rule based

        # First, try with a field based category (id)
        cats = []
        cats.append(QgsRendererCategory(1, QgsMarkerSymbol(), "id 1"))
        cats.append(QgsRendererCategory(2, QgsMarkerSymbol(), "id 2"))
        cats.append(QgsRendererCategory('a\'b', QgsMarkerSymbol(), "id a'b"))
        cats.append(QgsRendererCategory('a\nb', QgsMarkerSymbol(), "id a\\nb"))
        cats.append(QgsRendererCategory('a\\b', QgsMarkerSymbol(),
                                        "id a\\\\b"))
        cats.append(QgsRendererCategory('a\tb', QgsMarkerSymbol(), "id a\\tb"))
        cats.append(QgsRendererCategory(['c', 'd'], QgsMarkerSymbol(), "c/d"))
        c = QgsCategorizedSymbolRenderer("id", cats)

        r = QgsRuleBasedRenderer.convertFromRenderer(c)
        self.assertEqual(len(r.rootRule().children()), 7)
        self.assertEqual(r.rootRule().children()[0].filterExpression(),
                         '"id" = 1')
        self.assertEqual(r.rootRule().children()[1].filterExpression(),
                         '"id" = 2')
        self.assertEqual(r.rootRule().children()[2].filterExpression(),
                         '"id" = \'a\'\'b\'')
        self.assertEqual(r.rootRule().children()[3].filterExpression(),
                         '"id" = \'a\\nb\'')
        self.assertEqual(r.rootRule().children()[4].filterExpression(),
                         '"id" = \'a\\\\b\'')
        self.assertEqual(r.rootRule().children()[5].filterExpression(),
                         '"id" = \'a\\tb\'')
        self.assertEqual(r.rootRule().children()[6].filterExpression(),
                         '"id" IN (\'c\',\'d\')')

        # Next try with an expression based category
        cats = []
        cats.append(QgsRendererCategory(1, QgsMarkerSymbol(), "result 1"))
        cats.append(QgsRendererCategory(2, QgsMarkerSymbol(), "result 2"))
        cats.append(
            QgsRendererCategory([3, 4], QgsMarkerSymbol(), "result 3/4"))
        c = QgsCategorizedSymbolRenderer("id + 1", cats)

        r = QgsRuleBasedRenderer.convertFromRenderer(c)
        self.assertEqual(len(r.rootRule().children()), 3)
        self.assertEqual(r.rootRule().children()[0].filterExpression(),
                         'id + 1 = 1')
        self.assertEqual(r.rootRule().children()[1].filterExpression(),
                         'id + 1 = 2')
        self.assertEqual(r.rootRule().children()[2].filterExpression(),
                         'id + 1 IN (3,4)')

        # Last try with an expression which is just a quoted field name
        cats = []
        cats.append(QgsRendererCategory(1, QgsMarkerSymbol(), "result 1"))
        cats.append(QgsRendererCategory(2, QgsMarkerSymbol(), "result 2"))
        cats.append(
            QgsRendererCategory([3, 4], QgsMarkerSymbol(), "result 3/4"))
        c = QgsCategorizedSymbolRenderer('"id"', cats)

        r = QgsRuleBasedRenderer.convertFromRenderer(c)
        self.assertEqual(len(r.rootRule().children()), 3)
        self.assertEqual(r.rootRule().children()[0].filterExpression(),
                         '"id" = 1')
        self.assertEqual(r.rootRule().children()[1].filterExpression(),
                         '"id" = 2')
        self.assertEqual(r.rootRule().children()[2].filterExpression(),
                         '"id" IN (3,4)')
示例#30
0
    def testInitialSizeSymbolMapUnits(self):
        """Test initial size of legend with a symbol size in map units"""

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
        QgsProject.instance().addMapLayers([point_layer])

        marker_symbol = QgsMarkerSymbol.createSimple({
            'color': '#ff0000',
            'outline_style': 'no',
            'size': '5',
            'size_unit': 'MapUnit'
        })

        point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))

        s = QgsMapSettings()
        s.setLayers([point_layer])
        layout = QgsLayout(QgsProject.instance())
        layout.initializeDefaults()

        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map.setFrameEnabled(True)
        map.setLayers([point_layer])
        layout.addLayoutItem(map)
        map.setExtent(point_layer.extent())

        legend = QgsLayoutItemLegend(layout)
        legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        layout.addLayoutItem(legend)
        legend.setLinkedMap(map)

        checker = QgsLayoutChecker('composer_legend_mapunits', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.assertTrue(result, message)

        # resize with non-top-left reference point
        legend.setResizeToContents(False)
        legend.setReferencePoint(QgsLayoutItem.LowerRight)
        legend.attemptMove(QgsLayoutPoint(120, 90))
        legend.attemptResize(QgsLayoutSize(50, 60))

        self.assertEqual(legend.positionWithUnits().x(), 120.0)
        self.assertEqual(legend.positionWithUnits().y(), 90.0)
        self.assertAlmostEqual(legend.pos().x(), 70, -1)
        self.assertAlmostEqual(legend.pos().y(), 30, -1)

        legend.setResizeToContents(True)
        legend.updateLegend()
        self.assertEqual(legend.positionWithUnits().x(), 120.0)
        self.assertEqual(legend.positionWithUnits().y(), 90.0)
        self.assertAlmostEqual(legend.pos().x(), 91, -1)
        self.assertAlmostEqual(legend.pos().y(), 71, -1)

        QgsProject.instance().removeMapLayers([point_layer.id()])
示例#31
0
    def testSize(self):
        # test size and setSize

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbol()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        self.assertEqual(markerSymbol.size(), 10)
        markerSymbol.setSize(20)
        self.assertEqual(markerSymbol.size(), 20)
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 20)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=30))
        self.assertEqual(markerSymbol.size(), 30)
        markerSymbol.setSize(3)
        self.assertEqual(markerSymbol.size(), 3)
        # layer sizes should maintain relative size
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 2)
        self.assertEqual(markerSymbol.symbolLayer(1).size(), 1)
        self.assertEqual(markerSymbol.symbolLayer(2).size(), 3)
示例#32
0
    def testAngle(self):
        # test angle and setAngle

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbol()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10,
                                       angle=90))
        self.assertEqual(markerSymbol.angle(), 90)
        markerSymbol.setAngle(100)
        self.assertEqual(markerSymbol.angle(), 100)
        self.assertEqual(markerSymbol.symbolLayer(0).angle(), 100)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10,
                                       angle=130))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10,
                                       angle=150))
        # should take first layer's angle
        self.assertEqual(markerSymbol.angle(), 100)
        markerSymbol.setAngle(10)
        self.assertEqual(markerSymbol.angle(), 10)
        # layer angles should maintain relative angle
        self.assertEqual(markerSymbol.symbolLayer(0).angle(), 10)
        self.assertEqual(markerSymbol.symbolLayer(1).angle(), 40)
        self.assertEqual(markerSymbol.symbolLayer(2).angle(), 60)
示例#33
0
    def testSizeUnit(self):
        # test sizeUnit and setSizeUnit

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbol()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        self.assertEqual(markerSymbol.sizeUnit(),
                         QgsUnitTypes.RenderMillimeters)
        markerSymbol.setSizeUnit(QgsUnitTypes.RenderMapUnits)
        self.assertEqual(markerSymbol.sizeUnit(), QgsUnitTypes.RenderMapUnits)
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeUnit(),
            QgsUnitTypes.RenderMapUnits)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=30))
        # should now be mixed size units
        self.assertEqual(markerSymbol.sizeUnit(),
                         QgsUnitTypes.RenderUnknownUnit)
        markerSymbol.setSizeUnit(QgsUnitTypes.RenderPixels)
        self.assertEqual(markerSymbol.sizeUnit(), QgsUnitTypes.RenderPixels)
        # all layers should have size unit set
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeUnit(), QgsUnitTypes.RenderPixels)
        self.assertEqual(
            markerSymbol.symbolLayer(1).sizeUnit(), QgsUnitTypes.RenderPixels)
        self.assertEqual(
            markerSymbol.symbolLayer(2).sizeUnit(), QgsUnitTypes.RenderPixels)
示例#34
0
    def testSizeMapUnitScale(self):
        # test sizeMapUnitScale and setSizeMapUnitScale

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbol()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        markerSymbol.symbolLayer(0).setSizeMapUnitScale(
            QgsMapUnitScale(10000, 20000))
        self.assertEqual(markerSymbol.sizeMapUnitScale(),
                         QgsMapUnitScale(10000, 20000))
        markerSymbol.setSizeMapUnitScale(QgsMapUnitScale(1000, 2000))
        self.assertEqual(markerSymbol.sizeMapUnitScale(),
                         QgsMapUnitScale(1000, 2000))
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeMapUnitScale(),
            QgsMapUnitScale(1000, 2000))

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star,
                                       color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0),
                                       size=30))
        # should take first layer's map unit scale
        self.assertEqual(markerSymbol.sizeMapUnitScale(),
                         QgsMapUnitScale(1000, 2000))
        markerSymbol.setSizeMapUnitScale(QgsMapUnitScale(3000, 4000))
        self.assertEqual(markerSymbol.sizeMapUnitScale(),
                         QgsMapUnitScale(3000, 4000))
        # all layers should have size unit set
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeMapUnitScale(),
            QgsMapUnitScale(3000, 4000))
        self.assertEqual(
            markerSymbol.symbolLayer(1).sizeMapUnitScale(),
            QgsMapUnitScale(3000, 4000))
        self.assertEqual(
            markerSymbol.symbolLayer(2).sizeMapUnitScale(),
            QgsMapUnitScale(3000, 4000))
示例#35
0
    def legend_test(self):
        self.atlas_map.setAtlasDriven(True)
        self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Auto)
        self.atlas_map.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer(
            "Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)",
            "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRenderer("attr", [
            QgsRendererCategory(
                1,
                QgsMarkerSymbol.createSimple({
                    "color": "255,0,0",
                    'outline_color': 'black'
                }), "red"),
            QgsRendererCategory(
                2,
                QgsMarkerSymbol.createSimple({
                    "color": "0,0,255",
                    'outline_color': 'black'
                }), "blue")
        ])
        ptLayer.setRenderer(r)

        QgsProject.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.layers
        layers = [ptLayer] + layers
        self.atlas_map.setLayers(layers)
        self.overview.setLayers(layers)

        # add a legend
        legend = QgsLayoutItemLegend(self.layout)
        legend.attemptMove(QgsLayoutPoint(200, 100))
        # sets the legend filter parameter
        legend.setLinkedMap(self.atlas_map)
        legend.setLegendFilterOutAtlas(True)
        self.layout.addLayoutItem(legend)

        self.atlas.beginRender()

        self.atlas.seekTo(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsLayoutChecker('atlas_legend', self.layout)
        myTestResult, myMessage = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(myTestResult, myMessage)

        self.atlas.endRender()

        # restore state
        self.atlas_map.setLayers([layers[1]])
        self.layout.removeLayoutItem(legend)
        QgsProject.instance().removeMapLayer(ptLayer.id())
示例#36
0
    def run(self):

        global almacen
        #coloco el puntero arriba del todo
        QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint(
            QgsProject.instance().layerTreeRoot(), 0)

        #genero una lista con los sistemas de referencia
        misdatos = [["Etrs89 Zona30 (25830)", "25830"],
                    ["Etrs89 Zona29 (25829)", "25829"],
                    ["ED50 Zona30 (23030)", "23030"],
                    ["ED50_Zona29 (23029)", "23029"],
                    ["WGS84 geograficas sexagesimales(4326)", "4326"],
                    ["WGS84 geograficas centesimales(4326)", "4258"]]
        self.dlg.comboBox_src.clear()
        for element in misdatos:
            self.dlg.comboBox_src.addItem(element[0])
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False

        #leo la cache
        rutacache = os.path.join(QgsApplication.qgisSettingsDirPath(),
                                 r"python\plugins\zoomSigmena\cache.txt")
        if os.path.isfile(rutacache) == True:
            filecache = open(rutacache, "r")
            filecacheleido = filecache.readlines()
            try:
                import ast
                almacen = ast.literal_eval((filecacheleido[0].replace(
                    '\n', '')).replace(" [[",
                                       "[[").replace("]] ",
                                                     "]]"))  #.split(','))
                cache_utm = int(almacen[0])
                cache_geo = int(almacen[1])
                cache_escala = almacen[2]

                print(cache_escala)
                print(almacen)
                #miscomarcas=(filecacheleido[3].replace('\n','')).strip('][').split(',') #convierto una str en una list
                #mismunicipios=ast.literal_eval((filecacheleido[4].replace('\n','')).replace(" [[","[[").replace("]] ","]]"))#.split(',')) #convierto una str en una list
                filecache.close()

            except:
                print("esta no encuentra el file cache")
            self.dlg.lineEdit_escala.setText(str(cache_escala))
            self.dlg.checkBox_utm.setChecked(cache_utm)
            self.dlg.checkBox_geo.setChecked(cache_geo)
        # show the dialog
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            def deg_to_dms(deg, type='lat'):
                decimals, number = math.modf(deg)
                d = int(number)
                m = int(decimals * 60)
                s = (deg - d - m / 60) * 3600.00
                compass = {'lat': ('N', 'S'), 'lon': ('E', 'W')}
                compass_str = compass[type][0 if d >= 0 else 1]
                return '{}º{}\'{:.2f}"{}'.format(abs(d), abs(m), abs(s),
                                                 compass_str)

            #saco de  aqui variables que estan en las cajitas
            src_seleccionado = self.dlg.comboBox_src.currentIndex()

            # Get the coordinates and scale factor from the dialog
            x = self.dlg.XX.text()  ##displayText()
            y = self.dlg.YY.text()  ##displayText()
            escala = self.dlg.lineEdit_escala.text()

            x = x.replace(',', '.')
            y = y.replace(',', '.')
            escala = int(escala.replace('.', ''))
            src = misdatos[int(src_seleccionado)][1]

            if src == "4326":
                latext = y
                longtext = x

                lag = float(latext.split()[0])
                lam = float(latext.split()[1])
                las = float(latext.split()[2])
                log = float(longtext.split()[0])
                lom = float(longtext.split()[1])
                los = float(longtext.split()[2])

                lon = -1 * (log + (lom / 60) + (los / 3600))
                lat = lag + (lam / 60) + (las / 3600)

                x = float(lon)
                y = float(lat)
                print(x)
                print(y)
                huso = 30
                destinoProj = pyproj.Proj(proj="utm",
                                          zone=huso,
                                          ellps="WGS84",
                                          units="m")
                origenProj = pyproj.Proj(proj='longlat',
                                         ellps='WGS84',
                                         datum='WGS84')
                UTM_X, UTM_Y = pyproj.transform(origenProj, destinoProj, lon,
                                                lat)

            if src == "4258":
                print("por el camino adecuado")
                lat = float(y)
                lonn = float(x)
                lon = -1.0 * lonn

                print(lat)
                print(lon)

                huso = 30
                destinoProj = pyproj.Proj(proj="utm",
                                          zone=huso,
                                          ellps="WGS84",
                                          units="m")
                origenProj = pyproj.Proj(proj='longlat',
                                         ellps='WGS84',
                                         datum='WGS84')
                UTM_X, UTM_Y = pyproj.transform(origenProj, destinoProj, lon,
                                                lat)
                print(UTM_X)
                print(UTM_Y)
                x = lon
                y = lat

            #creo una capa temporal con las coordenadas

            # create layer
            vl2 = QgsVectorLayer("Point?crs=EPSG:" + src, "Zoom", "memory")
            pr2 = vl2.dataProvider()

            vl2.startEditing()
            # add fields

            pr2.addAttributes([
                QgsField("x", QVariant.Double),
                QgsField("y", QVariant.Double),
                QgsField("xx", QVariant.String),
                QgsField("yy", QVariant.String),
                QgsField("xxx", QVariant.Double),
                QgsField("yyy", QVariant.Double)
            ])
            vl2.updateFields()
            # tell the vector layer to fetch changes from the provider

            #$add a feature
            fet = QgsFeature()
            print("punto")
            print(x)
            print(y)
            fet.setGeometry(
                QgsGeometry.fromPointXY(QgsPointXY(float(x), float(y))))
            if src == "25830":
                huso = 30
                origenProj = pyproj.Proj(proj="utm",
                                         zone=huso,
                                         ellps="WGS84",
                                         units="m")
                destinoProj = pyproj.Proj(proj='longlat',
                                          ellps='WGS84',
                                          datum='WGS84')
                xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y)

                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))

            if src == "25829":
                huso = 29
                origenProj = pyproj.Proj(proj="utm",
                                         zone=huso,
                                         ellps="WGS84",
                                         units="m")
                destinoProj = pyproj.Proj(proj='longlat',
                                          ellps='WGS84',
                                          datum='WGS84')
                xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y)

                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))

            if src == "23030":
                huso = 30
                origenProj = pyproj.Proj(proj="utm",
                                         zone=huso,
                                         ellps="intl",
                                         units="m")
                destinoProj = pyproj.Proj(proj='longlat',
                                          ellps='WGS84',
                                          datum='WGS84')
                xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y)

                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))

            if src == "23029":
                huso = 29
                origenProj = pyproj.Proj(proj="utm",
                                         zone=huso,
                                         ellps="intl",
                                         units="m")
                destinoProj = pyproj.Proj(proj='longlat',
                                          ellps='WGS84',
                                          datum='WGS84')
                xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y)

                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))

            #para que lo pase a utms en pantalla
            if src == "4326":
                x = int(UTM_X)
                y = int(UTM_Y)
                #xx=longtext
                #yy=latext
                huso = 30
                origenProj = pyproj.Proj(proj="utm",
                                         zone=huso,
                                         ellps="intl",
                                         units="m")
                destinoProj = pyproj.Proj(proj='longlat',
                                          ellps='WGS84',
                                          datum='WGS84')
                xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y)
                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))
            #para que lo pase a utms en pantalla
            if src == "4258":
                x = int(UTM_X)
                y = int(UTM_Y)

                xxx = lon
                yyy = lat
                xx = (deg_to_dms(xxx, 'lon'))
                yy = (deg_to_dms(yyy))
            fet.setAttributes(
                [float(x),
                 float(y),
                 str(xx),
                 str(yy),
                 float(xxx),
                 float(yyy)])
            pr2.addFeatures([fet])

            #cambio la simbologia
            symbol = QgsMarkerSymbol.createSimple({
                'name': 'circle',
                'color': 'red',
                'size': '3',
            })
            vl2.renderer().setSymbol(symbol)

            # update layer's extent when new features have been added
            # because change of extent in provider is not propagated to the layer

            layer_settings = QgsPalLayerSettings()
            text_format = QgsTextFormat()

            text_format.setFont(QFont("Arial", 12))
            text_format.setSize(12)
            text_format.setColor(QColor("Orange"))

            layer_settings.setFormat(text_format)
            layer_settings.placement = 1
            layer_settings.xOffset = 0.0
            layer_settings.yOffset = 10.0
            mostrar = True
            if self.dlg.checkBox_utm.isChecked(
            ) and self.dlg.checkBox_geo.isChecked():
                layer_settings.fieldName = '''concat('X: ',"X",' Y: ',"Y",'\n','Lon: ',"xx",' Lat: ',"yy" )'''
                almacen = [1, 1]

            else:
                if self.dlg.checkBox_utm.isChecked():
                    layer_settings.fieldName = '''concat('X: ',"X",' Y: ',"Y" )'''
                    almacen = [1, 0]
                    print("caso1")
                if self.dlg.checkBox_geo.isChecked():
                    layer_settings.fieldName = '''concat('Lon: ',"xx",' Lat: ',"yy" )'''
                    almacen = [0, 1]
                    print("caso2")
                if not self.dlg.checkBox_utm.isChecked(
                ) and not self.dlg.checkBox_geo.isChecked():
                    mostrar = False
                    almacen = [0, 0]
                    print("caso3")
            print("almacen despues de etiquetar", almacen)
            layer_settings.isExpression = True

            print(mostrar)
            layer_settings.enabled = mostrar

            layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
            vl2.setLabelsEnabled(True)
            vl2.setLabeling(layer_settings)
            vl2.triggerRepaint()

            # update layer's extent when new features have been added
            # because change of extent in provider is not propagated to the layer
            vl2.updateExtents()
            vl2.commitChanges()
            vl2.updateExtents()
            canvas = self.iface.mapCanvas()
            canvas.setExtent(vl2.extent())

            crsSrc = QgsCoordinateReferenceSystem('EPSG:' + str(src))
            crsDest = QgsProject.instance().crs()

            if crsSrc != crsDest:

                xform = QgsCoordinateTransform(crsSrc, crsDest,
                                               QgsProject.instance())
                canvas.setExtent(xform.transform(vl2.extent()))

            self.iface.mapCanvas().zoomScale(escala)
            #self.limpiar_pressed()
            almacen.append(escala)
            #lo escribo en el txt, mavhacando lo que ya tenia
            f = open(rutacache, "w")
            escribir = str(almacen)
            f.write(escribir)
            f.close()
            print(almacen)
            QgsProject.instance().addMapLayer(vl2)
示例#37
0
 def setUp(self):
     # Create some simple symbols
     self.fill_symbol = QgsFillSymbol.createSimple({'color': '#ffffff', 'outline_color': 'black'})
     self.line_symbol = QgsLineSymbol.createSimple({'color': '#ffffff', 'line_width': '3'})
     self.marker_symbol = QgsMarkerSymbol.createSimple({'color': '#ffffff', 'size': '3', 'outline_color': 'black'})
     self.report = "<h1>Python QgsSymbol Tests</h1>\n"
示例#38
0
    def testLegendRenderWithMapTheme(self):
        """Test rendering legends linked to map themes"""
        QgsProject.instance().removeAllMapLayers()

        point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
        point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
        line_path = os.path.join(TEST_DATA_DIR, 'lines.shp')
        line_layer = QgsVectorLayer(line_path, 'lines', 'ogr')
        QgsProject.instance().clear()
        QgsProject.instance().addMapLayers([point_layer, line_layer])

        marker_symbol = QgsMarkerSymbol.createSimple({
            'color': '#ff0000',
            'outline_style': 'no',
            'size': '5'
        })
        point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))
        point_layer.styleManager().addStyleFromLayer("red")

        line_symbol = QgsLineSymbol.createSimple({
            'color': '#ff0000',
            'line_width': '2'
        })
        line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol))
        line_layer.styleManager().addStyleFromLayer("red")

        red_record = QgsMapThemeCollection.MapThemeRecord()
        point_red_record = QgsMapThemeCollection.MapThemeLayerRecord(
            point_layer)
        point_red_record.usingCurrentStyle = True
        point_red_record.currentStyle = 'red'
        red_record.addLayerRecord(point_red_record)
        line_red_record = QgsMapThemeCollection.MapThemeLayerRecord(line_layer)
        line_red_record.usingCurrentStyle = True
        line_red_record.currentStyle = 'red'
        red_record.addLayerRecord(line_red_record)
        QgsProject.instance().mapThemeCollection().insert('red', red_record)

        marker_symbol1 = QgsMarkerSymbol.createSimple({
            'color': '#0000ff',
            'outline_style': 'no',
            'size': '5'
        })
        marker_symbol2 = QgsMarkerSymbol.createSimple({
            'color': '#0000ff',
            'name': 'diamond',
            'outline_style': 'no',
            'size': '5'
        })
        marker_symbol3 = QgsMarkerSymbol.createSimple({
            'color': '#0000ff',
            'name': 'rectangle',
            'outline_style': 'no',
            'size': '5'
        })

        point_layer.setRenderer(
            QgsCategorizedSymbolRenderer('Class', [
                QgsRendererCategory('B52', marker_symbol1, ''),
                QgsRendererCategory('Biplane', marker_symbol2, ''),
                QgsRendererCategory('Jet', marker_symbol3, ''),
            ]))
        point_layer.styleManager().addStyleFromLayer("blue")

        line_symbol = QgsLineSymbol.createSimple({
            'color': '#0000ff',
            'line_width': '2'
        })
        line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol))
        line_layer.styleManager().addStyleFromLayer("blue")

        blue_record = QgsMapThemeCollection.MapThemeRecord()
        point_blue_record = QgsMapThemeCollection.MapThemeLayerRecord(
            point_layer)
        point_blue_record.usingCurrentStyle = True
        point_blue_record.currentStyle = 'blue'
        blue_record.addLayerRecord(point_blue_record)
        line_blue_record = QgsMapThemeCollection.MapThemeLayerRecord(
            line_layer)
        line_blue_record.usingCurrentStyle = True
        line_blue_record.currentStyle = 'blue'
        blue_record.addLayerRecord(line_blue_record)
        QgsProject.instance().mapThemeCollection().insert('blue', blue_record)

        layout = QgsLayout(QgsProject.instance())
        layout.initializeDefaults()

        map1 = QgsLayoutItemMap(layout)
        map1.attemptSetSceneRect(QRectF(20, 20, 80, 80))
        map1.setFrameEnabled(True)
        map1.setLayers([point_layer, line_layer])
        layout.addLayoutItem(map1)
        map1.setExtent(point_layer.extent())
        map1.setFollowVisibilityPreset(True)
        map1.setFollowVisibilityPresetName('red')

        map2 = QgsLayoutItemMap(layout)
        map2.attemptSetSceneRect(QRectF(20, 120, 80, 80))
        map2.setFrameEnabled(True)
        map2.setLayers([point_layer, line_layer])
        layout.addLayoutItem(map2)
        map2.setExtent(point_layer.extent())
        map2.setFollowVisibilityPreset(True)
        map2.setFollowVisibilityPresetName('blue')

        legend = QgsLayoutItemLegend(layout)
        legend.setTitle("Legend")
        legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
        legend.setFrameEnabled(True)
        legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend.setBackgroundColor(QColor(200, 200, 200))
        legend.setTitle('')
        layout.addLayoutItem(legend)
        legend.setLinkedMap(map1)

        legend2 = QgsLayoutItemLegend(layout)
        legend2.setTitle("Legend")
        legend2.attemptSetSceneRect(QRectF(120, 120, 80, 80))
        legend2.setFrameEnabled(True)
        legend2.setFrameStrokeWidth(QgsLayoutMeasurement(2))
        legend2.setBackgroundColor(QColor(200, 200, 200))
        legend2.setTitle('')
        layout.addLayoutItem(legend2)
        legend2.setLinkedMap(map2)

        checker = QgsLayoutChecker('composer_legend_theme', layout)
        checker.setControlPathPrefix("composer_legend")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        QgsProject.instance().clear()
示例#39
0
    def testRenderWithTransform(self):
        layer = QgsAnnotationLayer(
            'test',
            QgsAnnotationLayer.LayerOptions(
                QgsProject.instance().transformContext()))
        self.assertTrue(layer.isValid())

        item = QgsAnnotationPolygonItem(
            QgsPolygon(
                QgsLineString([
                    QgsPoint(11.5, 13),
                    QgsPoint(12, 13),
                    QgsPoint(12, 13.5),
                    QgsPoint(11.5, 13)
                ])))
        item.setSymbol(
            QgsFillSymbol.createSimple({
                'color': '200,100,100',
                'outline_color': 'black',
                'outline_width': '2'
            }))
        item.setZIndex(1)
        i1_id = layer.addItem(item)

        item = QgsAnnotationLineItem(
            QgsLineString(
                [QgsPoint(11, 13),
                 QgsPoint(12, 13),
                 QgsPoint(12, 15)]))
        item.setSymbol(
            QgsLineSymbol.createSimple({
                'color': '#ffff00',
                'line_width': '3'
            }))
        item.setZIndex(2)
        i2_id = layer.addItem(item)

        item = QgsAnnotationMarkerItem(QgsPoint(12, 13))
        item.setSymbol(
            QgsMarkerSymbol.createSimple({
                'color': '100,200,200',
                'size': '6',
                'outline_color': 'black'
            }))
        item.setZIndex(3)
        i3_id = layer.addItem(item)

        layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))

        settings = QgsMapSettings()
        settings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:3857'))
        settings.setExtent(QgsRectangle(1250958, 1386945, 1420709, 1532518))
        settings.setOutputSize(QSize(300, 300))

        settings.setFlag(QgsMapSettings.Antialiasing, False)

        rc = QgsRenderContext.fromMapSettings(settings)
        rc.setCoordinateTransform(
            QgsCoordinateTransform(layer.crs(), settings.destinationCrs(),
                                   QgsProject.instance()))
        rc.setExtent(rc.coordinateTransform().transformBoundingBox(
            settings.extent(), QgsCoordinateTransform.ReverseTransform))
        image = QImage(200, 200, QImage.Format_ARGB32)
        image.setDotsPerMeterX(int(96 / 25.4 * 1000))
        image.setDotsPerMeterY(int(96 / 25.4 * 1000))
        image.fill(QColor(255, 255, 255))
        painter = QPainter(image)
        rc.setPainter(painter)

        try:
            renderer = layer.createMapRenderer(rc)
            renderer.render()
        finally:
            painter.end()

        self.assertTrue(
            self.imageCheck('layer_render_transform', 'layer_render_transform',
                            image))

        # also check details of rendered items
        item_details = renderer.takeRenderedItemDetails()
        self.assertEqual([i.layerId() for i in item_details], [layer.id()] * 3)
        self.assertCountEqual([i.itemId() for i in item_details],
                              [i1_id, i2_id, i3_id])
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i1_id][0],
            QgsRectangle(11.5, 13, 12, 13.5))
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i2_id][0],
            QgsRectangle(11, 13, 12, 15))
        self.assertEqual([
            i.boundingBox().toString(2) for i in item_details
            if i.itemId() == i3_id
        ][0], '11.94,12.94 : 12.06,13.06')
示例#40
0
    def test_render_via_job(self):
        """
        Test rendering an annotation layer via a map render job
        """
        layer = QgsAnnotationLayer(
            'test',
            QgsAnnotationLayer.LayerOptions(
                QgsProject.instance().transformContext()))
        self.assertTrue(layer.isValid())

        item = QgsAnnotationPolygonItem(
            QgsPolygon(
                QgsLineString([
                    QgsPoint(11.5, 13),
                    QgsPoint(12, 13),
                    QgsPoint(12, 13.5),
                    QgsPoint(11.5, 13)
                ])))
        item.setSymbol(
            QgsFillSymbol.createSimple({
                'color': '200,100,100',
                'outline_color': 'black',
                'outline_width': '2'
            }))
        item.setZIndex(1)
        i1_id = layer.addItem(item)

        item = QgsAnnotationLineItem(
            QgsLineString(
                [QgsPoint(11, 13),
                 QgsPoint(12, 13),
                 QgsPoint(12, 15)]))
        item.setSymbol(
            QgsLineSymbol.createSimple({
                'color': '#ffff00',
                'line_width': '3'
            }))
        item.setZIndex(2)
        i2_id = layer.addItem(item)

        item = QgsAnnotationMarkerItem(QgsPoint(12, 13))
        item.setSymbol(
            QgsMarkerSymbol.createSimple({
                'color': '100,200,200',
                'size': '6',
                'outline_color': 'black'
            }))
        item.setZIndex(3)
        i3_id = layer.addItem(item)

        layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))

        settings = QgsMapSettings()
        settings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        settings.setExtent(QgsRectangle(10, 10, 18, 18))
        settings.setOutputSize(QSize(200, 200))
        settings.setLayers([layer])

        job = QgsMapRendererParallelJob(settings)
        job.start()
        job.waitForFinished()

        # check rendered item results
        item_results = job.takeRenderedItemResults()
        item_details = item_results.renderedItems()
        self.assertEqual(len(item_details), 3)
        self.assertEqual([i.layerId() for i in item_details], [layer.id()] * 3)
        self.assertCountEqual([i.itemId() for i in item_details],
                              [i1_id, i2_id, i3_id])
        self.assertCountEqual([
            i.itemId() for i in item_results.renderedAnnotationItemsInBounds(
                QgsRectangle(0, 0, 1, 1))
        ], [])
        self.assertCountEqual([
            i.itemId() for i in item_results.renderedAnnotationItemsInBounds(
                QgsRectangle(10, 10, 11, 18))
        ], [i2_id])
        self.assertCountEqual([
            i.itemId() for i in item_results.renderedAnnotationItemsInBounds(
                QgsRectangle(10, 10, 12, 18))
        ], [i1_id, i2_id, i3_id])

        # bounds should be in map crs
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i1_id][0],
            QgsRectangle(11.5, 13, 12, 13.5))
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i2_id][0],
            QgsRectangle(11, 13, 12, 15))
        self.assertEqual([
            i.boundingBox().toString(1) for i in item_details
            if i.itemId() == i3_id
        ][0], '11.5,12.5 : 12.5,13.5')
示例#41
0
    def testRenderLayerWithReferenceScale(self):
        layer = QgsAnnotationLayer(
            'test',
            QgsAnnotationLayer.LayerOptions(
                QgsProject.instance().transformContext()))
        layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        self.assertTrue(layer.isValid())

        item = QgsAnnotationPolygonItem(
            QgsPolygon(
                QgsLineString([
                    QgsPoint(12, 13),
                    QgsPoint(14, 13),
                    QgsPoint(14, 15),
                    QgsPoint(12, 13)
                ])))
        item.setSymbol(
            QgsFillSymbol.createSimple({
                'color': '200,100,100',
                'outline_color': 'black',
                'outline_width': '2'
            }))
        item.setZIndex(3)
        i1_id = layer.addItem(item)

        item = QgsAnnotationLineItem(
            QgsLineString(
                [QgsPoint(11, 13),
                 QgsPoint(12, 13),
                 QgsPoint(12, 15)]))
        item.setSymbol(
            QgsLineSymbol.createSimple({
                'color': '#ffff00',
                'line_width': '3'
            }))
        item.setZIndex(2)
        i2_id = layer.addItem(item)

        item = QgsAnnotationMarkerItem(QgsPoint(12, 13))
        item.setSymbol(
            QgsMarkerSymbol.createSimple({
                'color': '100,200,200',
                'size': '6',
                'outline_color': 'black'
            }))
        item.setZIndex(1)
        i3_id = layer.addItem(item)

        settings = QgsMapSettings()
        settings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        settings.setExtent(QgsRectangle(10, 10, 18, 18))
        settings.setOutputSize(QSize(300, 300))

        settings.setFlag(QgsMapSettings.Antialiasing, False)

        rc = QgsRenderContext.fromMapSettings(settings)

        layer.item(i1_id).setUseSymbologyReferenceScale(True)
        layer.item(i1_id).setSymbologyReferenceScale(rc.rendererScale() * 2)
        # note item 3 has use symbology reference scale set to false, so should be ignored
        layer.item(i2_id).setUseSymbologyReferenceScale(False)
        layer.item(i2_id).setSymbologyReferenceScale(rc.rendererScale() * 2)
        layer.item(i3_id).setUseSymbologyReferenceScale(True)
        layer.item(i3_id).setSymbologyReferenceScale(rc.rendererScale() * 2)

        image = QImage(200, 200, QImage.Format_ARGB32)
        image.setDotsPerMeterX(int(96 / 25.4 * 1000))
        image.setDotsPerMeterY(int(96 / 25.4 * 1000))
        image.fill(QColor(255, 255, 255))
        painter = QPainter(image)
        rc.setPainter(painter)

        try:
            renderer = layer.createMapRenderer(rc)
            renderer.render()
        finally:
            painter.end()

        self.assertTrue(
            self.imageCheck('layer_render_reference_scale',
                            'layer_render_reference_scale', image))

        # also check details of rendered items
        item_details = renderer.takeRenderedItemDetails()
        self.assertEqual([i.layerId() for i in item_details], [layer.id()] * 3)
        self.assertCountEqual([i.itemId() for i in item_details],
                              [i1_id, i2_id, i3_id])
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i1_id][0],
            QgsRectangle(12, 13, 14, 15))
        self.assertEqual(
            [i.boundingBox() for i in item_details if i.itemId() == i2_id][0],
            QgsRectangle(11, 13, 12, 15))
        self.assertEqual([
            i.boundingBox().toString(1) for i in item_details
            if i.itemId() == i3_id
        ][0], '11.4,12.4 : 12.6,13.6')
示例#42
0
    def test_render_via_job_with_transform(self):
        """
        Test rendering an annotation layer via a map render job
        """
        layer = QgsAnnotationLayer(
            'test',
            QgsAnnotationLayer.LayerOptions(
                QgsProject.instance().transformContext()))
        self.assertTrue(layer.isValid())

        item = QgsAnnotationPolygonItem(
            QgsPolygon(
                QgsLineString([
                    QgsPoint(11.5, 13),
                    QgsPoint(12, 13),
                    QgsPoint(12, 13.5),
                    QgsPoint(11.5, 13)
                ])))
        item.setSymbol(
            QgsFillSymbol.createSimple({
                'color': '200,100,100',
                'outline_color': 'black',
                'outline_width': '2'
            }))
        item.setZIndex(1)
        i1_id = layer.addItem(item)

        item = QgsAnnotationLineItem(
            QgsLineString(
                [QgsPoint(11, 13),
                 QgsPoint(12, 13),
                 QgsPoint(12, 15)]))
        item.setSymbol(
            QgsLineSymbol.createSimple({
                'color': '#ffff00',
                'line_width': '3'
            }))
        item.setZIndex(2)
        i2_id = layer.addItem(item)

        item = QgsAnnotationMarkerItem(QgsPoint(12, 13))
        item.setSymbol(
            QgsMarkerSymbol.createSimple({
                'color': '100,200,200',
                'size': '6',
                'outline_color': 'black'
            }))
        item.setZIndex(3)
        i3_id = layer.addItem(item)

        layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))

        settings = QgsMapSettings()
        settings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:3857'))
        settings.setExtent(QgsRectangle(1250958, 1386945, 1420709, 1532518))
        settings.setOutputSize(QSize(200, 200))
        settings.setLayers([layer])

        job = QgsMapRendererSequentialJob(settings)
        job.start()
        job.waitForFinished()

        # check rendered item results
        item_results = job.takeRenderedItemResults()
        item_details = item_results.renderedItems()
        self.assertEqual(len(item_details), 3)
        self.assertEqual([i.layerId() for i in item_details], [layer.id()] * 3)
        self.assertCountEqual([i.itemId() for i in item_details],
                              [i1_id, i2_id, i3_id])
        # bounds should be in map crs
        self.assertEqual(
            [
                QgsGeometry.fromRect(i.boundingBox()).asWkt(0)
                for i in item_details if i.itemId() == i1_id
            ][0],
            'Polygon ((1280174 1459732, 1335834 1459732, 1335834 1516914, 1280174 1516914, 1280174 1459732))'
        )
        self.assertEqual(
            [
                QgsGeometry.fromRect(i.boundingBox()).asWkt(0)
                for i in item_details if i.itemId() == i2_id
            ][0],
            'Polygon ((1224514 1459732, 1335834 1459732, 1335834 1689200, 1224514 1689200, 1224514 1459732))'
        )
        expected = 'Polygon ((1325786 1449684, 1345882 1449684, 1345882 1469780, 1325786 1469780, 1325786 1449684))'
        result = [
            QgsGeometry.fromRect(i.boundingBox()).asWkt(0)
            for i in item_details if i.itemId() == i3_id
        ][0]
        self.assertTrue(
            compareWkt(result, expected, tol=1000),
            "mismatch Expected:\n{}\nGot:\n{}\n".format(expected, result))
示例#43
0
    def testSize(self):
        # test size and setSize
        ms = QgsMapSettings()
        extent = QgsRectangle(100, 200, 100, 200)
        ms.setExtent(extent)
        ms.setOutputSize(QSize(400, 400))
        context = QgsRenderContext.fromMapSettings(ms)
        context.setScaleFactor(96 / 25.4)  # 96 DPI
        ms.setExtent(QgsRectangle(100, 150, 100, 150))
        ms.setOutputDpi(ms.outputDpi() * 2)
        context2 = QgsRenderContext.fromMapSettings(ms)
        context2.setScaleFactor(300 / 25.4)

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbol()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0), size=10))
        self.assertEqual(markerSymbol.size(), 10)
        self.assertAlmostEqual(markerSymbol.size(context), 37.795275590551185, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 118.11023622047244, 3)
        markerSymbol.setSize(20)
        self.assertEqual(markerSymbol.size(), 20)
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 20)
        self.assertAlmostEqual(markerSymbol.size(context), 75.59055118, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 236.2204724409449, 3)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0), size=10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0),
                                       strokeColor=QColor(0, 255, 0), size=30))
        self.assertEqual(markerSymbol.size(), 30)
        self.assertAlmostEqual(markerSymbol.size(context), 113.38582677165356, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 354.33070866141736, 3)

        markerSymbol.setSize(3)
        self.assertEqual(markerSymbol.size(), 3)
        # layer sizes should maintain relative size
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 2)
        self.assertEqual(markerSymbol.symbolLayer(1).size(), 1)
        self.assertEqual(markerSymbol.symbolLayer(2).size(), 3)

        # symbol layer in different size
        markerSymbol.symbolLayer(1).setSize(15)
        self.assertAlmostEqual(markerSymbol.size(context), 56.69291338582678, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 177.16535433070868, 3)
        markerSymbol.symbolLayer(1).setSizeUnit(QgsUnitTypes.RenderPixels)
        self.assertAlmostEqual(markerSymbol.size(context), 15, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 35.43307086614173, 3)
        markerSymbol.symbolLayer(1).setSize(45)
        self.assertAlmostEqual(markerSymbol.size(context), 45, 3)
        self.assertAlmostEqual(markerSymbol.size(context2), 45, 3)
示例#44
0
def saveSymbolLayerSprite(symbolLayer):
    sl = symbolLayer.clone()
    if isinstance(sl, QgsSVGFillSymbolLayer):
        patternWidth = sl.patternWidth()
        color = sl.svgFillColor()
        outlineColor = sl.svgOutlineColor()
        sl = QgsSvgMarkerSymbolLayer(sl.svgFilePath())
        sl.setFillColor(color)
        sl.setOutlineColor(outlineColor)
        sl.setSize(patternWidth)
        sl.setOutputUnit(QgsSymbol.Pixel)
    sl2x = sl.clone()
    try:
        sl2x.setSize(sl2x.size() * 2)
    except AttributeError:
        return None, None
    newSymbol = QgsMarkerSymbol()
    newSymbol.appendSymbolLayer(sl)
    newSymbol.deleteSymbolLayer(0)
    newSymbol2x = QgsMarkerSymbol()
    newSymbol2x.appendSymbolLayer(sl2x)
    newSymbol2x.deleteSymbolLayer(0)
    img = newSymbol.asImage(QSize(sl.size(), sl.size()))
    img2x = newSymbol2x.asImage(QSize(sl2x.size(), sl2x.size()))
    return img, img2x
示例#45
-1
    def testPasteSymbol(self):
        button = QgsSymbolButton()
        button.setSymbolType(QgsSymbol.Marker)
        symbol = QgsMarkerSymbol.createSimple({})
        symbol.setColor(QColor(255, 0, 0))
        button.setSymbol(symbol)

        button2 = QgsSymbolButton()
        button2.setSymbolType(QgsSymbol.Marker)
        symbol2 = QgsMarkerSymbol.createSimple({})
        symbol2.setColor(QColor(0, 255, 0))
        button2.setSymbol(symbol2)

        button.copySymbol()
        button2.pasteSymbol()
        self.assertEqual(button2.symbol().color(), QColor(255, 0, 0))

        # try pasting incompatible symbol
        button2.setSymbolType(QgsSymbol.Fill)
        fill_symbol = QgsFillSymbol.createSimple({})
        fill_symbol.setColor(QColor(0, 0, 255))
        button2.setSymbol(fill_symbol)
        button.copySymbol() # copied a marker symbol
        button2.pasteSymbol() # should have no effect
        self.assertEqual(button2.symbol(), fill_symbol)
示例#46
-1
    def legend_test(self):
        self.atlas_map.setAtlasDriven(True)
        self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Auto)
        self.atlas_map.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)", "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRenderer("attr", [QgsRendererCategory(1, QgsMarkerSymbol.createSimple({"color": "255,0,0", 'outline_color': 'black'}), "red"),
                                                  QgsRendererCategory(2, QgsMarkerSymbol.createSimple({"color": "0,0,255", 'outline_color': 'black'}), "blue")])
        ptLayer.setRenderer(r)

        QgsProject.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.layers
        layers = [ptLayer] + layers
        self.atlas_map.setLayers(layers)
        self.overview.setLayers(layers)

        # add a legend
        legend = QgsLayoutItemLegend(self.layout)
        legend.setTitle("Legend")
        legend.attemptMove(QgsLayoutPoint(200, 100))
        # sets the legend filter parameter
        legend.setLinkedMap(self.atlas_map)
        legend.setLegendFilterOutAtlas(True)
        self.layout.addLayoutItem(legend)

        self.atlas.beginRender()

        self.atlas.seekTo(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsLayoutChecker('atlas_legend', self.layout)
        myTestResult, myMessage = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(myTestResult, myMessage)

        self.atlas.endRender()

        # restore state
        self.atlas_map.setLayers([layers[1]])
        self.layout.removeLayoutItem(legend)
        QgsProject.instance().removeMapLayer(ptLayer.id())