def testConvertToMapUnits(self): ms = QgsMapSettings() ms.setExtent(QgsRectangle(0, 0, 100, 100)) ms.setOutputSize(QSize(100, 50)) ms.setOutputDpi(300) r = QgsRenderContext.fromMapSettings(ms) # renderer scale should be about 1:291937841 # start with no min/max scale c = QgsMapUnitScale() size = r.convertToMapUnits(2, QgsUnitTypes.RenderMapUnits, c) self.assertEqual(size, 2.0) size = r.convertToMapUnits(2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 47.244094, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 47.2440833, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderInches, c) self.assertAlmostEqual(size, 3401.574, places=5) size = r.convertToMapUnits(2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 4.0, places=5) # minimum size greater than the calculated size, so size should be limited to minSizeMM c.minSizeMM = 5 c.minSizeMMEnabled = True size = r.convertToMapUnits(2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 118.1102362, places=5) # only conversion from mapunits should be affected size = r.convertToMapUnits(2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 47.244094, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 47.2440833, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderInches, c) self.assertAlmostEqual(size, 3401.574, places=5) size = r.convertToMapUnits(2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 4.0, places=5) c.minSizeMMEnabled = False # maximum size less than the calculated size, so size should be limited to maxSizeMM c.maxSizeMM = 0.05 c.maxSizeMMEnabled = True size = r.convertToMapUnits(2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 1.1811023622047245, places=5) # only conversion from mapunits should be affected size = r.convertToMapUnits(2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 47.244094, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 47.2440833, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderInches, c) self.assertAlmostEqual(size, 3401.574, places=5) size = r.convertToMapUnits(2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 4.0, places=5) c.maxSizeMMEnabled = False # test with minimum scale set c.minScale = 150000000.0 size = r.convertToMapUnits(2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 15.57001821, places=5) # only conversion from mapunits should be affected size = r.convertToMapUnits(2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 47.244094, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 47.2440833, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderInches, c) self.assertAlmostEqual(size, 3401.574, places=5) size = r.convertToMapUnits(2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 4.0, places=5) c.minScale = 0 # test with maximum scale set c.maxScale = 1550000000.0 size = r.convertToMapUnits(2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 1.50677595625, places=5) # only conversion from mapunits should be affected size = r.convertToMapUnits(2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 47.244094, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 47.2440833, places=5) size = r.convertToMapUnits(5.66929, QgsUnitTypes.RenderInches, c) self.assertAlmostEqual(size, 3401.574, places=5) size = r.convertToMapUnits(2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 4.0, places=5) c.maxScale = 0
def testRenderLayer(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) 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', 'layer_render', 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.7,12.7 : 12.3,13.3')
def __init__(self, text): QPushButton.__init__(self) self.setText(text) buttons_size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setSizePolicy(buttons_size_policy) self.setMaximumSize(QSize(30, 30))
def __init__(self, map_theme, layer, extent, tile_size, mupp, output, make_trans, map_settings, project): """ :param map_theme: :param extent: :param layer: :param tile_size: :param mupp: :param output: :param map_settings: Map canvas map settings used for some fallback values and CRS """ self.extent = extent self.mupp = mupp self.tile_size = tile_size driver = self.getDriverForFile(output) if not driver: raise QgsProcessingException( u'Could not load GDAL driver for file {}'.format(output)) crs = map_settings.destinationCrs() self.x_tile_count = math.ceil(extent.width() / mupp / tile_size) self.y_tile_count = math.ceil(extent.height() / mupp / tile_size) xsize = self.x_tile_count * tile_size ysize = self.y_tile_count * tile_size if make_trans: no_bands = 4 else: no_bands = 3 self.dataset = driver.Create(output, xsize, ysize, no_bands) self.dataset.SetProjection(str(crs.toWkt())) self.dataset.SetGeoTransform( [extent.xMinimum(), mupp, 0, extent.yMaximum(), 0, -mupp]) self.image = QImage(QSize(tile_size, tile_size), QImage.Format_ARGB32) self.settings = QgsMapSettings() self.settings.setOutputDpi(self.image.logicalDpiX()) self.settings.setOutputImageFormat(QImage.Format_ARGB32) self.settings.setDestinationCrs(crs) self.settings.setOutputSize(self.image.size()) self.settings.setFlag(QgsMapSettings.Antialiasing, True) self.settings.setFlag(QgsMapSettings.RenderMapTile, True) self.settings.setFlag(QgsMapSettings.UseAdvancedEffects, True) r = project.readNumEntry('Gui', '/CanvasColorRedPart', 255)[0] g = project.readNumEntry('Gui', '/CanvasColorGreenPart', 255)[0] b = project.readNumEntry('Gui', '/CanvasColorBluePart', 255)[0] if make_trans: self.bgColor = QColor(r, g, b, 0) else: self.bgColor = QColor(r, g, b) self.settings.setBackgroundColor(self.bgColor) if QgsProject.instance().mapThemeCollection().hasMapTheme(map_theme): self.settings.setLayers(QgsProject.instance().mapThemeCollection(). mapThemeVisibleLayers(map_theme)) self.settings.setLayerStyleOverrides(QgsProject.instance( ).mapThemeCollection().mapThemeStyleOverrides(map_theme)) elif layer: self.settings.setLayers([layer]) else: self.settings.setLayers(map_settings.layers())
def testExportToImage(self): md = QgsProject.instance().metadata() md.setTitle('proj title') md.setAuthor('proj author') md.setCreationDateTime(QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000))) md.setIdentifier('proj identifier') md.setAbstract('proj abstract') md.setKeywords({'kw': ['kw1', 'kw2']}) QgsProject.instance().setMetadata(md) l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.ImageExportSettings() settings.dpi = 80 rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagedpi.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertTrue(self.checkImage('exporttoimagedpi_page1', 'exporttoimagedpi_page1', rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagedpi_2.png') self.assertTrue(self.checkImage('exporttoimagedpi_page2', 'exporttoimagedpi_page2', page2_path)) for f in (rendered_file_path, page2_path): d = gdal.Open(f) metadata = d.GetMetadata() self.assertEqual(metadata['Author'], 'proj author') self.assertEqual(metadata['Created'], '2011-05-03T09:04:05+10:00') self.assertIn(metadata['Keywords'], ('kw1,kw2', 'kw2,kw1')) self.assertEqual(metadata['Subject'], 'proj abstract') self.assertEqual(metadata['Title'], 'proj title') # crop to contents settings.cropToContents = True settings.cropMargins = QgsMargins(10, 20, 30, 40) rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagecropped.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertTrue(self.checkImage('exporttoimagecropped_page1', 'exporttoimagecropped_page1', rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagecropped_2.png') self.assertTrue(self.checkImage('exporttoimagecropped_page2', 'exporttoimagecropped_page2', page2_path)) # specific pages settings.cropToContents = False settings.pages = [1] rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagepages.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertFalse(os.path.exists(rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagepages_2.png') self.assertTrue(self.checkImage('exporttoimagedpi_page2', 'exporttoimagedpi_page2', page2_path)) # image size settings.imageSize = QSize(600, 851) rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagesize.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertFalse(os.path.exists(rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagesize_2.png') self.assertTrue(self.checkImage('exporttoimagesize_page2', 'exporttoimagesize_page2', page2_path))
def test_signalConnection(self): # remove all layers QgsProject.instance().removeAllMapLayers() # set dependencies and add back layers self.pointsLayer = QgsVectorLayer( "dbname='%s' table=\"node\" (geom) sql=" % self.fn, "points", "spatialite") assert (self.pointsLayer.isValid()) self.linesLayer = QgsVectorLayer( "dbname='%s' table=\"section\" (geom) sql=" % self.fn, "lines", "spatialite") assert (self.linesLayer.isValid()) self.pointsLayer2 = QgsVectorLayer( "dbname='%s' table=\"node2\" (geom) sql=" % self.fn, "_points2", "spatialite") assert (self.pointsLayer2.isValid()) self.pointsLayer.setDependencies( [QgsMapLayerDependency(self.linesLayer.id())]) self.pointsLayer2.setDependencies( [QgsMapLayerDependency(self.pointsLayer.id())]) # this should update connections between layers QgsProject.instance().addMapLayers([self.pointsLayer]) QgsProject.instance().addMapLayers([self.linesLayer]) QgsProject.instance().addMapLayers([self.pointsLayer2]) ms = QgsMapSettings() ms.setOutputSize(QSize(100, 100)) ms.setExtent(QgsRectangle(0, 0, 1, 1)) self.assertTrue(ms.hasValidSettings()) u = QgsSnappingUtils() u.setMapSettings(ms) cfg = u.config() cfg.setEnabled(True) cfg.setMode(QgsSnappingConfig.AdvancedConfiguration) cfg.setIndividualLayerSettings( self.pointsLayer, QgsSnappingConfig.IndividualLayerSettings(True, QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) cfg.setIndividualLayerSettings( self.pointsLayer2, QgsSnappingConfig.IndividualLayerSettings(True, QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) u.setConfig(cfg) # add another line f = QgsFeature(self.linesLayer.fields()) f.setId(4) geom = QgsGeometry.fromWkt("LINESTRING(0.5 0.2,0.6 0)") f.setGeometry(geom) self.linesLayer.startEditing() self.linesLayer.addFeatures([f]) self.linesLayer.commitChanges() # check the second snapped point is OK m = u.snapToMap(QPoint(75, 100 - 0)) self.assertTrue(m.isValid()) self.assertTrue(m.hasVertex()) self.assertEqual(m.point(), QgsPointXY(0.8, 0.0)) self.pointsLayer.setDependencies([]) self.pointsLayer2.setDependencies([])
def test_resetSnappingIndex(self): self.pointsLayer.setDependencies([]) self.linesLayer.setDependencies([]) self.pointsLayer2.setDependencies([]) ms = QgsMapSettings() ms.setOutputSize(QSize(100, 100)) ms.setExtent(QgsRectangle(0, 0, 1, 1)) self.assertTrue(ms.hasValidSettings()) u = QgsSnappingUtils() u.setMapSettings(ms) cfg = u.config() cfg.setEnabled(True) cfg.setMode(QgsSnappingConfig.AdvancedConfiguration) cfg.setIndividualLayerSettings( self.pointsLayer, QgsSnappingConfig.IndividualLayerSettings(True, QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) u.setConfig(cfg) m = u.snapToMap(QPoint(95, 100)) self.assertTrue(m.isValid()) self.assertTrue(m.hasVertex()) self.assertEqual(m.point(), QgsPointXY(1, 0)) f = QgsFeature(self.linesLayer.fields()) f.setId(1) geom = QgsGeometry.fromWkt("LINESTRING(0 0,1 1)") f.setGeometry(geom) self.linesLayer.startEditing() self.linesLayer.addFeatures([f]) self.linesLayer.commitChanges() l1 = len([f for f in self.pointsLayer.getFeatures()]) self.assertEqual(l1, 4) m = u.snapToMap(QPoint(95, 0)) # snapping not updated self.pointsLayer.setDependencies([]) self.assertEqual(m.isValid(), False) # set layer dependencies self.pointsLayer.setDependencies( [QgsMapLayerDependency(self.linesLayer.id())]) # add another line f = QgsFeature(self.linesLayer.fields()) f.setId(2) geom = QgsGeometry.fromWkt("LINESTRING(0 0,0.5 0.5)") f.setGeometry(geom) self.linesLayer.startEditing() self.linesLayer.addFeatures([f]) self.linesLayer.commitChanges() # check the snapped point is OK m = u.snapToMap(QPoint(45, 50)) self.assertTrue(m.isValid()) self.assertTrue(m.hasVertex()) self.assertEqual(m.point(), QgsPointXY(0.5, 0.5)) self.pointsLayer.setDependencies([]) # test chained layer dependencies A -> B -> C cfg.setIndividualLayerSettings( self.pointsLayer2, QgsSnappingConfig.IndividualLayerSettings(True, QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) u.setConfig(cfg) self.pointsLayer.setDependencies( [QgsMapLayerDependency(self.linesLayer.id())]) self.pointsLayer2.setDependencies( [QgsMapLayerDependency(self.pointsLayer.id())]) # add another line f = QgsFeature(self.linesLayer.fields()) f.setId(3) geom = QgsGeometry.fromWkt("LINESTRING(0 0.2,0.5 0.8)") f.setGeometry(geom) self.linesLayer.startEditing() self.linesLayer.addFeatures([f]) self.linesLayer.commitChanges() # check the second snapped point is OK m = u.snapToMap(QPoint(75, 100 - 80)) self.assertTrue(m.isValid()) self.assertTrue(m.hasVertex()) self.assertEqual(m.point(), QgsPointXY(0.7, 0.8)) self.pointsLayer.setDependencies([]) self.pointsLayer2.setDependencies([])
def setUp(self): self.iface = get_iface() self.iface.mapCanvas().viewport().resize(400, 400) # For some reason the resizeEvent is not delivered, fake it self.iface.mapCanvas().resizeEvent(QResizeEvent(QSize(400, 400), self.iface.mapCanvas().size()))
def testConvertToPainterUnits(self): # test QgsSymbolLayerUtils::convertToPainterUnits() using QgsMapUnitScale ms = QgsMapSettings() ms.setExtent(QgsRectangle(0, 0, 100, 100)) ms.setOutputSize(QSize(100, 50)) ms.setOutputDpi(300) r = QgsRenderContext.fromMapSettings(ms) # renderer scale should be about 1:291937841 # start with no min/max scale c = QgsMapUnitScale() size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 1.0, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 23.622047, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 66.9601332, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 2.0, places=5) # minimum size greater than the calculated size, so size should be limited to minSizeMM c.minSizeMM = 5 c.minSizeMMEnabled = True size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 59.0551181, places=5) # only conversion from mapunits should be affected size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 23.622047, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 66.9601332, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 2.0, places=5) c.minSizeMMEnabled = False # maximum size less than the calculated size, so size should be limited to maxSizeMM c.maxSizeMM = 0.1 c.maxSizeMMEnabled = True size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMapUnits, c) self.assertAlmostEqual(size, 1.0, places=5) # only conversion from mapunits should be affected size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderMillimeters, c) self.assertAlmostEqual(size, 23.622047, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPoints, c) self.assertAlmostEqual(size, 66.9601332, places=5) size = QgsSymbolLayerUtils.convertToPainterUnits( r, 2, QgsUnitTypes.RenderPixels, c) self.assertAlmostEqual(size, 2.0, places=5)