def testTableMultiFrame(self): """Test we can render to multiframes.""" layout_html = QgsLayoutItemHtml(self.layout) html_frame = QgsLayoutFrame(self.layout, layout_html) html_frame.attemptSetSceneRect(QRectF(10, 10, 100, 50)) layout_html.addFrame(html_frame) layout_html.setResizeMode( QgsLayoutMultiFrame.RepeatUntilFinished) layout_html.setUseSmartBreaks(False) layout_html.setUrl(self.htmlUrl()) layout_html.frame(0).setFrameEnabled(True) print("Checking page 1") myPage = 0 checker1 = QgsLayoutChecker('composerhtml_multiframe1', self.layout) checker1.setControlPathPrefix("composer_html") myTestResult, myMessage = checker1.testLayout(myPage) assert myTestResult, myMessage print("Checking page 2") myPage = 1 checker2 = QgsLayoutChecker('composerhtml_multiframe2', self.layout) checker2.setControlPathPrefix("composer_html") myTestResult, myMessage = checker2.testLayout(myPage) assert myTestResult, myMessage self.layout.removeMultiFrame(layout_html) layout_html = None assert myTestResult, myMessage
def testInteriorTicks(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setBackgroundColor(QColor(150, 100, 100)) layout.addLayoutItem(map) map.grid().setFrameStyle(QgsLayoutItemMapGrid.Zebra) myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375, 3345223.125) map.setExtent(myRectangle) map.grid().setIntervalX(2000) map.grid().setIntervalY(2000) map.grid().setAnnotationFontColor(QColor(0, 0, 0)) map.grid().setBlendMode(QPainter.CompositionMode_SourceOver) map.grid().setFrameStyle(QgsLayoutItemMapGrid.InteriorTicks) map.grid().setFrameWidth(10) map.grid().setFramePenSize(1) map.grid().setFramePenColor(QColor(0, 0, 0)) map.grid().setEnabled(True) map.grid().setStyle(QgsLayoutItemMapGrid.FrameAnnotationsOnly) map.updateBoundingRect() checker = QgsLayoutChecker('composermap_interiorticks', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout(0, 100) assert myTestResult, myMessage
def testZebraStyle(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setBackgroundColor(QColor(150, 100, 100)) layout.addLayoutItem(map) map.grid().setFrameStyle(QgsLayoutItemMapGrid.Zebra) myRectangle = QgsRectangle(785462.375, 3341423.125, 789262.375, 3343323.125) map.setExtent(myRectangle) map.grid().setIntervalX(2000) map.grid().setIntervalY(2000) map.grid().setGridLineColor(QColor(0, 0, 0)) map.grid().setAnnotationFontColor(QColor(0, 0, 0)) map.grid().setBlendMode(QPainter.CompositionMode_SourceOver) map.grid().setFrameStyle(QgsLayoutItemMapGrid.Zebra) map.grid().setFrameWidth(10) map.grid().setFramePenSize(1) map.grid().setGridLineWidth(0.5) map.grid().setFramePenColor(QColor(255, 100, 0, 200)) map.grid().setFrameFillColor1(QColor(50, 90, 50, 100)) map.grid().setFrameFillColor2(QColor(200, 220, 100, 60)) map.grid().setEnabled(True) map.updateBoundingRect() checker = QgsLayoutChecker('composermap_zebrastyle', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout(0, 100) assert myTestResult, myMessage
def testCrossGrid(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setBackgroundColor(QColor(150, 100, 100)) layout.addLayoutItem(map) myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375, 3345223.125) map.setExtent(myRectangle) map.grid().setEnabled(True) map.grid().setStyle(QgsLayoutItemMapGrid.Cross) map.grid().setCrossLength(2.0) map.grid().setIntervalX(2000) map.grid().setIntervalY(2000) map.grid().setAnnotationEnabled(False) map.grid().setGridLineColor(QColor(0, 255, 0)) map.grid().setGridLineWidth(0.5) map.grid().setBlendMode(QPainter.CompositionMode_SourceOver) map.updateBoundingRect() checker = QgsLayoutChecker('composermap_crossgrid', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() map.grid().setStyle(QgsLayoutItemMapGrid.Solid) map.grid().setEnabled(False) map.grid().setAnnotationEnabled(False) assert myTestResult, myMessage
def autoscale_render_test(self): self.atlas_map.setExtent( QgsRectangle(332719.06221504929, 6765214.5887386119, 560957.85090677091, 6993453.3774303338)) self.atlas_map.setAtlasDriven(True) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Auto) self.atlas_map.setAtlasMargin(0.10) self.atlas.beginRender() for i in range(0, 2): self.atlas.seekTo(i) self.mLabel1.adjustSizeToText() checker = QgsLayoutChecker('atlas_autoscale%d' % (i + 1), self.layout) checker.setControlPathPrefix("atlas") myTestResult, myMessage = checker.testLayout(0, 200) self.report += checker.report() self.assertTrue(myTestResult, myMessage) self.atlas.endRender() self.atlas_map.setAtlasDriven(False) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Fixed) self.atlas_map.setAtlasMargin(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.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 testResizeZoom(self): """Test picture resize zoom mode.""" self.picture.setResizeMode(QgsLayoutItemPicture.Zoom) checker = QgsLayoutChecker('composerpicture_resize_zoom', self.layout) checker.setControlPathPrefix("composer_picture") testResult, message = checker.testLayout() assert testResult, message
def testDefaultStyle(self): """Test polygon rendering with default style.""" self.polygon.setDisplayNodes(False) checker = QgsLayoutChecker( 'composerpolygon_defaultstyle', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage
def testExpressionInText(self): """Test expressions embedded in legend node text""" point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') layout = QgsPrintLayout(QgsProject.instance()) layout.setName('LAYOUT') 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, 100, 100)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') legend.setLegendFilterByMapEnabled(False) legend.setStyleFont(QgsLegendStyle.Title, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Group, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Subgroup, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Symbol, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.SymbolLabel, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setAutoUpdateModel(False) QgsProject.instance().addMapLayers([point_layer]) s = QgsMapSettings() s.setLayers([point_layer]) group = legend.model().rootGroup().addGroup("Group [% 1 + 5 %] [% @layout_name %]") layer_tree_layer = group.addLayer(point_layer) layer_tree_layer.setCustomProperty("legend/title-label", 'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]') QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0, 'xxxx') legend.model().refreshLayerLegend(layer_tree_layer) legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel('bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]') layout.addLayoutItem(legend) legend.setLinkedMap(map) map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30)) checker = QgsLayoutChecker( 'composer_legend_expressions', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.assertTrue(result, message) QgsProject.instance().removeMapLayers([point_layer.id()])
def testRemoteImage(self): """Test fetching remote picture.""" self.picture.setPicturePath('http://localhost:' + str(TestQgsLayoutPicture.port) + '/qgis_local_server/logo.png') checker = QgsLayoutChecker('picture_remote', self.layout) checker.setControlPathPrefix("composer_picture") testResult, message = checker.testLayout() self.picture.setPicturePath(self.pngImage) assert testResult, message
def testEndArrow(self): self.polyline.setEndMarker(QgsLayoutItemPolyline.ArrowHead) self.polyline.setArrowHeadWidth(30.0) checker = QgsLayoutChecker('composerpolyline_endArrow', self.layout) checker.setControlPathPrefix("composer_polyline") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage self.polyline.setEndMarker(QgsLayoutItemPolyline.NoMarker)
def testRemoveNode(self): """Test removeNode method""" rc = self.polygon.removeNode(100) self.assertEqual(rc, False) checker = QgsLayoutChecker( 'composerpolygon_defaultstyle', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage self.assertEqual(self.polygon.nodesSize(), 4)
def testMoveNode(self): """Test moveNode method""" rc = self.polygon.moveNode(30, QPointF(100.0, 300.0)) self.assertEqual(rc, False) rc = self.polygon.moveNode(3, QPointF(100.0, 150.0)) self.assertEqual(rc, True) checker = QgsLayoutChecker( 'composerpolygon_movenode', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage
def testDisplayNodes(self): """Test displayNodes method""" self.polygon.setDisplayNodes(True) checker = QgsLayoutChecker( 'composerpolygon_displaynodes', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage self.polygon.setDisplayNodes(False) checker = QgsLayoutChecker( 'composerpolygon_defaultstyle', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage
def testTable(self): """Test we can render a html table in a single frame.""" layout_html = QgsLayoutItemHtml(self.layout) html_frame = QgsLayoutFrame(self.layout, layout_html) html_frame.attemptSetSceneRect(QRectF(0, 0, 100, 200)) html_frame.setFrameEnabled(True) layout_html.addFrame(html_frame) layout_html.setUrl(self.htmlUrl()) checker = QgsLayoutChecker('composerhtml_table', self.layout) checker.setControlPathPrefix("composer_html") myTestResult, myMessage = checker.testLayout() qDebug(myMessage) self.layout.removeMultiFrame(layout_html) assert myTestResult, myMessage
def testMapCrs(self): # create layout with layout map map_settings = QgsMapSettings() map_settings.setLayers([self.vector_layer]) layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() # check that new maps inherit project CRS QgsProject.instance().setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) rectangle = QgsRectangle(-13838977, 2369660, -8672298, 6250909) map.setExtent(rectangle) map.setLayers([self.vector_layer]) layout.addLayoutItem(map) self.assertEqual(map.crs().authid(), 'EPSG:4326') self.assertFalse(map.presetCrs().isValid()) # overwrite CRS map.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) self.assertEqual(map.crs().authid(), 'EPSG:3857') self.assertEqual(map.presetCrs().authid(), 'EPSG:3857') checker = QgsLayoutChecker('composermap_crs3857', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # overwrite CRS map.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) self.assertEqual(map.presetCrs().authid(), 'EPSG:4326') self.assertEqual(map.crs().authid(), 'EPSG:4326') rectangle = QgsRectangle(-124, 17, -78, 52) map.zoomToExtent(rectangle) checker = QgsLayoutChecker('composermap_crs4326', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # change back to project CRS map.setCrs(QgsCoordinateReferenceSystem()) self.assertEqual(map.crs().authid(), 'EPSG:4326') self.assertFalse(map.presetCrs().isValid())
def fixedscale_render_test(self): self.atlas_map.setExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620)) self.atlas_map.setAtlasDriven(True) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Fixed) self.atlas.beginRender() for i in range(0, 2): self.atlas.seekTo(i) self.mLabel1.adjustSizeToText() checker = QgsLayoutChecker('atlas_fixedscale%d' % (i + 1), self.layout) checker.setControlPathPrefix("atlas") myTestResult, myMessage = checker.testLayout(0, 200) self.report += checker.report() self.assertTrue(myTestResult, myMessage) self.atlas.endRender()
def testOverviewMapBlend(self): overviewMap = QgsLayoutItemMap(self.layout) overviewMap.attemptSetSceneRect(QRectF(20, 130, 70, 70)) overviewMap.setFrameEnabled(True) overviewMap.setLayers([self.raster_layer]) self.layout.addLayoutItem(overviewMap) # zoom in myRectangle = QgsRectangle(96, -152, 160, -120) self.map.setExtent(myRectangle) myRectangle2 = QgsRectangle(0, -256, 256, 0) overviewMap.setExtent(myRectangle2) overviewMap.overview().setFrameMap(self.map) overviewMap.overview().setBlendMode(QPainter.CompositionMode_Multiply) checker = QgsLayoutChecker('composermap_overview_blending', self.layout) checker.setControlPathPrefix("composer_mapoverview") myTestResult, myMessage = checker.testLayout() self.layout.removeLayoutItem(overviewMap) assert myTestResult, myMessage
def testSelectedNode(self): """Test selectedNode and deselectNode methods""" self.polygon.setDisplayNodes(True) self.polygon.setSelectedNode(3) checker = QgsLayoutChecker( 'composerpolygon_selectednode', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage self.polygon.deselectNode() self.polygon.setDisplayNodes(False) checker = QgsLayoutChecker( 'composerpolygon_defaultstyle', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage
def testOverviewMap(self): overviewMap = QgsLayoutItemMap(self.layout) overviewMap.attemptSetSceneRect(QRectF(20, 130, 70, 70)) overviewMap.setFrameEnabled(True) overviewMap.setLayers([self.raster_layer]) self.layout.addLayoutItem(overviewMap) # zoom in myRectangle = QgsRectangle(96, -152, 160, -120) self.map.setExtent(myRectangle) myRectangle2 = QgsRectangle(0, -256, 256, 0) overviewMap.setExtent(myRectangle2) overviewMap.overview().setLinkedMap(self.map) checker = QgsLayoutChecker('composermap_overview', self.layout) checker.setColorTolerance(6) checker.setControlPathPrefix("composer_mapoverview") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.layout.removeLayoutItem(overviewMap) assert myTestResult, myMessage
def testOverviewMapCenter(self): overviewMap = QgsLayoutItemMap(self.layout) overviewMap.attemptSetSceneRect(QRectF(20, 130, 70, 70)) overviewMap.setFrameEnabled(True) overviewMap.setLayers([self.raster_layer]) self.layout.addLayoutItem(overviewMap) # zoom in myRectangle = QgsRectangle(192, -288, 320, -224) self.map.setExtent(myRectangle) myRectangle2 = QgsRectangle(0, -256, 256, 0) overviewMap.setExtent(myRectangle2) overviewMap.overview().setFrameMap(self.map) overviewMap.overview().setInverted(False) overviewMap.overview().setCentered(True) checker = QgsLayoutChecker('composermap_overview_center', self.layout) checker.setControlPathPrefix("composer_mapoverview") myTestResult, myMessage = checker.testLayout() self.layout.removeLayoutItem(overviewMap) assert myTestResult, myMessage
def testResizeDisabledCrop(self): """Test that if legend resizing is disabled, and legend is too small, then content is cropped""" point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') QgsProject.instance().addMapLayers([point_layer]) 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, 20, 20)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') legend.setLegendFilterByMapEnabled(True) # disable auto resizing legend.setResizeToContents(False) layout.addLayoutItem(legend) legend.setLinkedMap(map) map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30)) checker = QgsLayoutChecker( 'composer_legend_noresize_crop', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.assertTrue(result, message) QgsProject.instance().removeMapLayers([point_layer.id()])
def testAddNodeWithoutCheckingArea(self): """Test addNode without checking the maximum distance allowed""" # default searching radius is 10 self.assertEqual(self.polygon.nodesSize(), 4) rc = self.polygon.addNode(QPointF(50.0, 20.0)) self.assertEqual(rc, False) self.assertEqual(self.polygon.nodesSize(), 4) # default searching radius is 10 self.assertEqual(self.polygon.nodesSize(), 4) rc = self.polygon.addNode(QPointF(50.0, 20.0), False) self.assertEqual(rc, True) self.assertEqual(self.polygon.nodesSize(), 5) checker = QgsLayoutChecker( 'composerpolygon_addnode', self.layout) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testLayout() assert myTestResult, myMessage
def testOverviewStacking(self): l = QgsLayout(QgsProject.instance()) l.initializeDefaults() map = QgsLayoutItemMap(l) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setLayers([self.raster_layer]) l.addLayoutItem(map) overviewMap = QgsLayoutItemMap(l) overviewMap.attemptSetSceneRect(QRectF(20, 130, 70, 70)) l.addLayoutItem(overviewMap) overviewMap.setFrameEnabled(True) overviewMap.setLayers([self.raster_layer]) # zoom in myRectangle = QgsRectangle(96, -152, 160, -120) map.setExtent(myRectangle) myRectangle2 = QgsRectangle(-20, -276, 276, 20) overviewMap.setExtent(myRectangle2) overviewMap.overview().setLinkedMap(map) overviewMap.overview().setInverted(True) overviewMap.overview().setStackingPosition(QgsLayoutItemMapItem.StackBelowMapLayer) overviewMap.overview().setStackingLayer(self.raster_layer) checker = QgsLayoutChecker('composermap_overview_belowmap', l) checker.setColorTolerance(6) checker.setControlPathPrefix("composer_mapoverview") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage) overviewMap.overview().setStackingPosition(QgsLayoutItemMapItem.StackAboveMapLayer) overviewMap.overview().setStackingLayer(self.raster_layer) checker = QgsLayoutChecker('composermap_overview_abovemap', l) checker.setColorTolerance(6) checker.setControlPathPrefix("composer_mapoverview") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage)
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()])
def sorting_render_test(self): self.atlas_map.setExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620)) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Fixed) self.atlas.setHideCoverage(False) self.atlas.setSortFeatures(True) self.atlas.setSortKeyAttributeIndex(4) # departement name self.atlas.setSortAscending(False) self.atlas.beginRender() for i in range(0, 2): self.atlas.seekTo(i) self.mLabel1.adjustSizeToText() checker = QgsLayoutChecker('atlas_sorting%d' % (i + 1), self.layout) checker.setControlPathPrefix("atlas") myTestResult, myMessage = checker.testLayout(0, 200) self.report += checker.report() self.assertTrue(myTestResult, myMessage) self.atlas.endRender()
def testGrid(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setBackgroundColor(QColor(150, 100, 100)) layout.addLayoutItem(map) """Test that we can create a grid for a map.""" myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375, 3345223.125) map.setExtent(myRectangle) map.grid().setEnabled(True) map.grid().setIntervalX(2000) map.grid().setIntervalY(2000) map.grid().setAnnotationEnabled(True) map.grid().setGridLineColor(QColor(0, 255, 0)) map.grid().setGridLineWidth(0.5) map.grid().setAnnotationFont(QgsFontUtils.getStandardTestFont()) map.grid().setAnnotationPrecision(0) map.grid().setAnnotationDisplay(QgsLayoutItemMapGrid.HideAll, QgsLayoutItemMapGrid.Left) map.grid().setAnnotationPosition(QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationDisplay(QgsLayoutItemMapGrid.HideAll, QgsLayoutItemMapGrid.Top) map.grid().setAnnotationPosition(QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.Bottom) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.Horizontal, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.Horizontal, QgsLayoutItemMapGrid.Bottom) map.grid().setAnnotationFontColor(QColor(255, 0, 0, 150)) map.grid().setBlendMode(QPainter.CompositionMode_Overlay) map.updateBoundingRect() checker = QgsLayoutChecker('composermap_grid', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() map.grid().setEnabled(False) map.grid().setAnnotationEnabled(False) assert myTestResult, myMessage
def renderAnnotationInLayout(self, test_name, annotation): pr = QgsProject() l = QgsLayout(pr) l.initializeDefaults() map = QgsLayoutItemMap(l) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) rectangle = QgsRectangle(0, 0, 18, 8) map.setExtent(rectangle) l.addLayoutItem(map) annotation.setMapPosition(QgsPointXY(1, 7)) annotation.setHasFixedMapPosition(True) pr.annotationManager().addAnnotation(annotation) checker = QgsLayoutChecker( test_name, l) checker.dots_per_meter = 2 * 96 / 25.4 * 1000 checker.size = QSize(1122 * 2, 794 * 2) checker.setControlPathPrefix("annotations") result, message = checker.testLayout() self.report += checker.report() return result
def predefinedscales_render_test(self): self.atlas_map.setExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620)) self.atlas_map.setAtlasDriven(True) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Predefined) scales = [1800000, 5000000] self.layout.reportContext().setPredefinedScales(scales) for i, s in enumerate(self.layout.reportContext().predefinedScales()): self.assertEqual(s, scales[i]) self.atlas.beginRender() for i in range(0, 2): self.atlas.seekTo(i) self.mLabel1.adjustSizeToText() checker = QgsLayoutChecker('atlas_predefinedscales%d' % (i + 1), self.layout) checker.setControlPathPrefix("atlas") myTestResult, myMessage = checker.testLayout(0, 200) self.report += checker.report() self.assertTrue(myTestResult, myMessage) self.atlas.endRender()
def filtering_render_test(self): self.atlas_map.setExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620)) self.atlas_map.setAtlasScalingMode(QgsLayoutItemMap.Fixed) self.atlas.setHideCoverage(False) self.atlas.setSortFeatures(False) self.atlas.setFilterFeatures(True) self.atlas.setFeatureFilter("substr(NAME_1,1,1)='P'") # select only 'Pays de la loire' self.atlas.beginRender() for i in range(0, 1): self.atlas.seekTo(i) self.mLabel1.adjustSizeToText() checker = QgsLayoutChecker('atlas_filtering%d' % (i + 1), self.layout) checker.setControlPathPrefix("atlas") myTestResult, myMessage = checker.testLayout(0, 200) self.report += checker.report() self.assertTrue(myTestResult, myMessage) self.atlas.endRender()
def testClippingHideClipSource(self): """ When an item is set to be the clip source, it shouldn't render anything itself """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(30) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'XXXX'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Polygon?crs=epsg:4326&field=id:integer", "vl", "memory") props = { "color": "127,255,127", 'outline_style': 'solid', 'outline_width': '1', 'outline_color': '0,0,255' } fillSymbol = QgsFillSymbol.createSimple(props) renderer = QgsSingleSymbolRenderer(fillSymbol) vl.setRenderer(renderer) f = QgsFeature(vl.fields(), 1) for x in range(0, 15, 3): for y in range(0, 15, 3): f.setGeometry(QgsGeometry(QgsPoint(x, y)).buffer(1, 3)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(False) map.zoomToExtent(vl.extent()) map.setLayers([vl]) layout.addLayoutItem(map) shape = QgsLayoutItemShape(layout) layout.addLayoutItem(shape) shape.setShapeType(QgsLayoutItemShape.Ellipse) shape.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.itemClippingSettings().setEnabled(True) map.itemClippingSettings().setSourceItem(shape) map.itemClippingSettings().setForceLabelsInsideClipPath(False) map.itemClippingSettings().setFeatureClippingType( QgsMapClippingRegion.FeatureClippingType.ClipToIntersection) checker = QgsLayoutChecker('composermap_itemclip_nodrawsource', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() TestQgsLayoutMap.report += checker.report() self.assertTrue(result, message)
def testAnnotationsVariationsRotated(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map_configs = [ (10, 30, QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.InteriorTicks, 0), (10, 120, QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.InteriorTicks, 3), (90, 30, QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.ExteriorTicks, 0), (90, 120, QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.ExteriorTicks, 3), (170, 30, QgsLayoutItemMapGrid.InsideMapFrame, QgsLayoutItemMapGrid.InteriorTicks, 0), (170, 120, QgsLayoutItemMapGrid.InsideMapFrame, QgsLayoutItemMapGrid.InteriorTicks, 3), (250, 30, QgsLayoutItemMapGrid.InsideMapFrame, QgsLayoutItemMapGrid.ExteriorTicks, 0), (250, 120, QgsLayoutItemMapGrid.InsideMapFrame, QgsLayoutItemMapGrid.ExteriorTicks, 3), ] for x, y, pos, style, dist in map_configs: map = QgsLayoutItemMap(layout) layout.addLayoutItem(map) map.attemptSetSceneRect(QRectF(x, y, 50, 50)) map.setBackgroundColor(QColor(200, 200, 200)) map.setExtent(QgsRectangle(5, 5, 15, 15)) map.setMapRotation(30) map.setFrameEnabled(True) map.grid().setFrameStyle(style) map.grid().setFrameWidth(7) map.grid().setFramePenSize(1) map.grid().setFramePenColor(QColor(255, 0, 0)) map.grid().setEnabled(True) map.grid().setIntervalX(10) map.grid().setIntervalY(10) map.grid().setAnnotationEnabled(True) map.grid().setGridLineColor(QColor(0, 255, 0)) map.grid().setGridLineWidth(0.5) map.grid().setAnnotationFont(getTestFont('Bold', 20)) map.grid().setAnnotationFontColor(QColor(0, 0, 255, 150)) map.grid().setAnnotationPrecision(0) map.grid().setAnnotationFrameDistance(dist) map.grid().setRotatedTicksEnabled(True) map.grid().setRotatedAnnotationsEnabled(True) map.grid().setAnnotationPosition(pos, QgsLayoutItemMapGrid.Top) map.grid().setAnnotationPosition(pos, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationPosition(pos, QgsLayoutItemMapGrid.Bottom) map.grid().setAnnotationPosition(pos, QgsLayoutItemMapGrid.Left) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.AboveTick, QgsLayoutItemMapGrid.Top) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.OnTick, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.UnderTick, QgsLayoutItemMapGrid.Bottom) map.grid().setAnnotationDirection( QgsLayoutItemMapGrid.BoundaryDirection, QgsLayoutItemMapGrid.Left) map.updateBoundingRect() checker = QgsLayoutChecker( 'composermap_annotations_variations_rotated', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() self.assertTrue(myTestResult, myMessage)
def testLegendRenderLinkedMapScale(self): """Test rendering legends linked to maps follow scale correctly""" QgsProject.instance().removeAllMapLayers() line_path = os.path.join(TEST_DATA_DIR, 'lines.shp') line_layer = QgsVectorLayer(line_path, 'lines', 'ogr') QgsProject.instance().clear() QgsProject.instance().addMapLayers([line_layer]) line_symbol = QgsLineSymbol.createSimple({ 'color': '#ff0000', 'width_unit': 'mapunits', 'width': '0.0001' }) line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol)) layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map1 = QgsLayoutItemMap(layout) map1.attemptSetSceneRect(QRectF(20, 20, 80, 80)) map1.setFrameEnabled(True) map1.setLayers([line_layer]) layout.addLayoutItem(map1) map1.setExtent(line_layer.extent()) map1.setScale(2000) map2 = QgsLayoutItemMap(layout) map2.attemptSetSceneRect(QRectF(20, 120, 80, 80)) map2.setFrameEnabled(True) map2.setLayers([line_layer]) layout.addLayoutItem(map2) map2.setExtent(line_layer.extent()) map2.setScale(5000) 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_scale_map', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() TestQgsLayoutItemLegend.report += checker.report() self.assertTrue(result, message) QgsProject.instance().clear()
def testLabelMargin(self): """ Test rendering map item with a label margin set """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) layout.addLayoutItem(map) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin(QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters)) checker = QgsLayoutChecker('composermap_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin(QgsLayoutMeasurement(3, QgsUnitTypes.LayoutCentimeters)) checker = QgsLayoutChecker('composermap_label_cm_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setMapRotation(45) map.zoomToExtent(vl.extent()) map.setScale(map.scale() * 1.2) checker = QgsLayoutChecker('composermap_rotated_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # data defined map.setMapRotation(0) map.zoomToExtent(vl.extent()) map.dataDefinedProperties().setProperty(QgsLayoutObject.MapLabelMargin, QgsProperty.fromExpression('1+3')) map.refresh() checker = QgsLayoutChecker('composermap_dd_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
def testDynamicInterval(self): layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 200, 100)) map.setFrameEnabled(True) map.setBackgroundColor(QColor(150, 100, 100)) layout.addLayoutItem(map) myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375, 3345223.125) map.setExtent(myRectangle) map.grid().setEnabled(True) map.grid().setUnits(QgsLayoutItemMapGrid.DynamicPageSizeBased) map.grid().setMinimumIntervalWidth(50) map.grid().setMaximumIntervalWidth(100) map.grid().setAnnotationEnabled(True) map.grid().setGridLineColor(QColor(0, 255, 0)) map.grid().setGridLineWidth(0.5) format = QgsTextFormat.fromQFont(getTestFont('Bold', 20)) format.setColor(QColor(255, 0, 0)) format.setOpacity(150 / 255) map.grid().setAnnotationTextFormat(format) map.grid().setAnnotationPrecision(0) map.grid().setAnnotationDisplay(QgsLayoutItemMapGrid.HideAll, QgsLayoutItemMapGrid.Left) map.grid().setAnnotationPosition(QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationDisplay(QgsLayoutItemMapGrid.HideAll, QgsLayoutItemMapGrid.Top) map.grid().setAnnotationPosition(QgsLayoutItemMapGrid.OutsideMapFrame, QgsLayoutItemMapGrid.Bottom) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.Horizontal, QgsLayoutItemMapGrid.Right) map.grid().setAnnotationDirection(QgsLayoutItemMapGrid.Horizontal, QgsLayoutItemMapGrid.Bottom) map.grid().setBlendMode(QPainter.CompositionMode_Overlay) map.updateBoundingRect() map.grid().refresh() checker = QgsLayoutChecker('composermap_dynamic_5_10', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage) map.setScale(map.scale() * 1.1) checker = QgsLayoutChecker('composermap_dynamic_5_10_2', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage) map.setScale(map.scale() * 1.8) checker = QgsLayoutChecker('composermap_dynamic_5_10_3', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage) map.grid().setMinimumIntervalWidth(10) map.grid().setMaximumIntervalWidth(40) map.grid().refresh() checker = QgsLayoutChecker('composermap_dynamic_5_10_4', layout) checker.setControlPathPrefix("composer_mapgrid") myTestResult, myMessage = checker.testLayout() self.report += checker.report() self.assertTrue(myTestResult, myMessage)
def testPartialLabels(self): """ Test rendering map item with a show partial labels flag """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) layout.addLayoutItem(map) # default should always be to hide partial labels self.assertFalse(map.mapFlags() & QgsLayoutItemMap.ShowPartialLabels) # hiding partial labels (the default) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # showing partial labels map.setMapFlags(QgsLayoutItemMap.ShowPartialLabels) checker = QgsLayoutChecker('composermap_show_partial_labels', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
def testBlockingItems(self): """ Test rendering map item with blocking items """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) map.setId('map') layout.addLayoutItem(map) map2 = QgsLayoutItemMap(layout) map2.attemptSetSceneRect(QRectF(0, 5, 50, 80)) map2.setFrameEnabled(True) map2.setBackgroundEnabled(False) map2.setId('map2') layout.addLayoutItem(map2) map3 = QgsLayoutItemMap(layout) map3.attemptSetSceneRect(QRectF(150, 160, 50, 50)) map3.setFrameEnabled(True) map3.setBackgroundEnabled(False) map3.setId('map3') layout.addLayoutItem(map3) map.addLabelBlockingItem(map2) map.addLabelBlockingItem(map3) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_blockers', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) doc = QDomDocument("testdoc") elem = layout.writeXml(doc, QgsReadWriteContext()) l2 = QgsLayout(p) self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext())) map_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map'][0] map2_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map2'][0] map3_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map3'][0] self.assertTrue(map_restore.isLabelBlockingItem(map2_restore)) self.assertTrue(map_restore.isLabelBlockingItem(map3_restore))
def testExpressionInText(self): """Test expressions embedded in legend node text""" point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') layout = QgsPrintLayout(QgsProject.instance()) layout.setName('LAYOUT') 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, 100, 100)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') legend.setLegendFilterByMapEnabled(False) legend.setStyleFont(QgsLegendStyle.Title, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Group, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Subgroup, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.Symbol, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setStyleFont(QgsLegendStyle.SymbolLabel, QgsFontUtils.getStandardTestFont('Bold', 16)) legend.setAutoUpdateModel(False) QgsProject.instance().addMapLayers([point_layer]) s = QgsMapSettings() s.setLayers([point_layer]) group = legend.model().rootGroup().addGroup( "Group [% 1 + 5 %] [% @layout_name %]") layer_tree_layer = group.addLayer(point_layer) layer_tree_layer.setCustomProperty( "legend/title-label", 'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]') QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0, 'xxxx') legend.model().refreshLayerLegend(layer_tree_layer) legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel( 'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]') layout.addLayoutItem(legend) legend.setLinkedMap(map) map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30)) checker = QgsLayoutChecker('composer_legend_expressions', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.assertTrue(result, message) QgsProject.instance().removeMapLayers([point_layer.id()])
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 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() TestQgsLayoutItemLegend.report += checker.report() self.assertTrue(result, message) QgsProject.instance().clear()