def testTakeLayer(self): # test taking ownership of a layer from the project l1 = createLayer('l1') l2 = createLayer('l2') p = QgsProject() # add one layer to project p.addMapLayer(l1) self.assertEqual(p.mapLayers(), {l1.id(): l1}) self.assertEqual(l1.parent().parent(), p) # try taking some layers which don't exist in project self.assertFalse(p.takeMapLayer(None)) self.assertFalse(p.takeMapLayer(l2)) # but l2 should still exist.. self.assertTrue(l2.isValid()) # take layer from project self.assertEqual(p.takeMapLayer(l1), l1) self.assertFalse(p.mapLayers()) # no layers left # but l1 should still exist self.assertTrue(l1.isValid()) # layer should have no parent now self.assertFalse(l1.parent()) # destroy project p = None self.assertTrue(l1.isValid())
def testSaveLoadProject(self): schema_uri = encode_uri(self.ds_uri, 'qgis_test') project_uri = encode_uri(self.ds_uri, 'qgis_test', 'abc') self.dropProjectsTable() # make sure we have a clean start prj = QgsProject() uri = self.vl.source() vl1 = QgsVectorLayer(uri, 'test', 'postgres') self.assertEqual(vl1.isValid(), True) prj.addMapLayer(vl1) prj_storage = QgsApplication.projectStorageRegistry().projectStorageFromType("postgresql") self.assertTrue(prj_storage) lst0 = prj_storage.listProjects(schema_uri) self.assertEqual(lst0, []) # try to save project in the database prj.setFileName(project_uri) res = prj.write() self.assertTrue(res) lst1 = prj_storage.listProjects(schema_uri) self.assertEqual(lst1, ["abc"]) # now try to load the project back prj2 = QgsProject() prj2.setFileName(project_uri) res = prj2.read() self.assertTrue(res) self.assertEqual(len(prj2.mapLayers()), 1) self.assertEqual(prj2.baseName(), "abc") self.assertEqual(prj2.absoluteFilePath(), "") # path not supported for project storages self.assertTrue(abs(prj2.lastModified().secsTo(QDateTime.currentDateTime())) < 10) # try to see project's metadata res, metadata = prj_storage.readProjectStorageMetadata(project_uri) self.assertTrue(res) self.assertEqual(metadata.name, "abc") time_project = metadata.lastModified time_now = QDateTime.currentDateTime() time_diff = time_now.secsTo(time_project) self.assertTrue(abs(time_diff) < 10) # try to remove the project res = prj_storage.removeProject(project_uri) self.assertTrue(res) lst2 = prj_storage.listProjects(schema_uri) self.assertEqual(lst2, []) self.dropProjectsTable() # make sure we have a clean finish... "leave no trace"
def testReplaceLayerWhileOpen(self): ''' Replace an existing geopackage layer whilst it's open in the project''' tmpfile = os.path.join(self.basetestpath, 'testGeopackageReplaceOpenLayer.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) lyr = ds.CreateLayer('layer1', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('attr', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('attr2', ogr.OFTInteger)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 0)')) lyr.CreateFeature(f) f = None vl1 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer1", u'layer1', u'ogr') p = QgsProject() p.addMapLayer(vl1) request = QgsFeatureRequest().setSubsetOfAttributes([0]) features = [f for f in vl1.getFeatures(request)] self.assertEqual(len(features), 1) # now, overwrite the layer with a different geometry type and fields ds.DeleteLayer('layer1') lyr = ds.CreateLayer('layer1', geom_type=ogr.wkbLineString) lyr.CreateField(ogr.FieldDefn('attr', ogr.OFTString)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('LineString(0 0, 1 1)')) lyr.CreateFeature(f) f = None vl2 = QgsVectorLayer(u'{}'.format(tmpfile) + "|layername=layer1", u'layer2', u'ogr') p.addMapLayer(vl2) features = [f for f in vl1.getFeatures(request)] self.assertEqual(len(features), 1)
def testReadWriteXml(self): p = QgsProject() ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=country:string(20)&field=state:string(20)&field=town:string(20)", "points", "memory") p.addMapLayer(ptLayer) r = QgsReport(p) r.setName('my report') # add a header r.setHeaderEnabled(True) report_header = QgsLayout(p) report_header.setUnits(QgsUnitTypes.LayoutInches) r.setHeader(report_header) # add a footer r.setFooterEnabled(True) report_footer = QgsLayout(p) report_footer.setUnits(QgsUnitTypes.LayoutMeters) r.setFooter(report_footer) # add some subsections child1 = QgsReportSectionLayout() child1_body = QgsLayout(p) child1_body.setUnits(QgsUnitTypes.LayoutPoints) child1.setBody(child1_body) child2 = QgsReportSectionLayout() child2_body = QgsLayout(p) child2_body.setUnits(QgsUnitTypes.LayoutPixels) child2.setBody(child2_body) child1.appendChild(child2) child2a = QgsReportSectionFieldGroup() child2a_body = QgsLayout(p) child2a_body.setUnits(QgsUnitTypes.LayoutInches) child2a.setBody(child2a_body) child2a.setField('my field') child2a.setLayer(ptLayer) child1.appendChild(child2a) r.appendChild(child1) doc = QDomDocument("testdoc") elem = r.writeLayoutXml(doc, QgsReadWriteContext()) r2 = QgsReport(p) self.assertTrue(r2.readLayoutXml(elem, doc, QgsReadWriteContext())) self.assertEqual(r2.name(), 'my report') self.assertTrue(r2.headerEnabled()) self.assertEqual(r2.header().units(), QgsUnitTypes.LayoutInches) self.assertTrue(r2.footerEnabled()) self.assertEqual(r2.footer().units(), QgsUnitTypes.LayoutMeters) self.assertEqual(r2.childCount(), 1) self.assertEqual(r2.childSection(0).body().units(), QgsUnitTypes.LayoutPoints) self.assertEqual(r2.childSection(0).childCount(), 2) self.assertEqual(r2.childSection(0).childSection(0).body().units(), QgsUnitTypes.LayoutPixels) self.assertEqual(r2.childSection(0).childSection(1).body().units(), QgsUnitTypes.LayoutInches) self.assertEqual(r2.childSection(0).childSection(1).field(), 'my field') self.assertEqual(r2.childSection(0).childSection(1).layer(), ptLayer)
def testNameForPage(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setCoverageLayer(vector_layer) atlas.setPageNameExpression("\"NAME_1\"") self.assertTrue(atlas.beginRender()) self.assertEqual(atlas.nameForPage(0), 'Basse-Normandie') self.assertEqual(atlas.nameForPage(1), 'Bretagne') self.assertEqual(atlas.nameForPage(2), 'Pays de la Loire') self.assertEqual(atlas.nameForPage(3), 'Centre')
def test_mapLayersByName(self): """ test retrieving map layer by name """ p = QgsProject() # test no crash with empty registry self.assertEqual(p.mapLayersByName('bad'), []) self.assertEqual(p.mapLayersByName(None), []) l1 = createLayer('test') l2 = createLayer('test2') p.addMapLayers([l1, l2]) self.assertEqual(p.mapLayersByName('bad'), []) self.assertEqual(p.mapLayersByName(None), []) self.assertEqual(p.mapLayersByName('test'), [l1]) self.assertEqual(p.mapLayersByName('test2'), [l2]) #duplicate name l3 = createLayer('test') p.addMapLayer(l3) self.assertEqual(set(p.mapLayersByName('test')), set([l1, l3]))
def testUpdateFeature(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setCoverageLayer(vector_layer) self.assertTrue(atlas.beginRender()) self.assertTrue(atlas.first()) self.assertEqual(atlas.currentFeatureNumber(), 0) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') self.assertEqual(l.reportContext().layer(), vector_layer) vector_layer.startEditing() self.assertTrue(vector_layer.changeAttributeValue(l.reportContext().feature().id(), 4, 'Nah, Canberra mate!')) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') l.atlas().refreshCurrentFeature() self.assertEqual(l.reportContext().feature()[4], 'Nah, Canberra mate!') vector_layer.rollBack()
def testFileName(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setCoverageLayer(vector_layer) atlas.setFilenameExpression("'output_' || \"NAME_1\"") self.assertTrue(atlas.beginRender()) self.assertEqual(atlas.count(), 4) atlas.first() self.assertEqual(atlas.currentFilename(), 'output_Basse-Normandie') self.assertEqual(atlas.filePath('/tmp/output/', 'png'), '/tmp/output/output_Basse-Normandie.png') self.assertEqual(atlas.filePath('/tmp/output/', '.png'), '/tmp/output/output_Basse-Normandie.png') self.assertEqual(atlas.filePath('/tmp/output/', 'svg'), '/tmp/output/output_Basse-Normandie.svg') atlas.next() self.assertEqual(atlas.currentFilename(), 'output_Bretagne') self.assertEqual(atlas.filePath('/tmp/output/', 'png'), '/tmp/output/output_Bretagne.png') atlas.next() self.assertEqual(atlas.currentFilename(), 'output_Pays de la Loire') self.assertEqual(atlas.filePath('/tmp/output/', 'png'), '/tmp/output/output_Pays de la Loire.png') atlas.next() self.assertEqual(atlas.currentFilename(), 'output_Centre') self.assertEqual(atlas.filePath('/tmp/output/', 'png'), '/tmp/output/output_Centre.png') # try changing expression, filename should be updated instantly atlas.setFilenameExpression("'export_' || \"NAME_1\"") self.assertEqual(atlas.currentFilename(), 'export_Centre') atlas.endRender()
def testReadWriteXml(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setHideCoverage(True) atlas.setFilenameExpression('filename exp') atlas.setCoverageLayer(vector_layer) atlas.setPageNameExpression('page name') atlas.setSortFeatures(True) atlas.setSortAscending(False) atlas.setSortExpression('sort exp') atlas.setFilterFeatures(True) atlas.setFilterExpression('filter exp') doc = QDomDocument("testdoc") elem = l.writeXml(doc, QgsReadWriteContext()) l2 = QgsPrintLayout(p) self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext())) atlas2 = l2.atlas() self.assertTrue(atlas2.enabled()) self.assertTrue(atlas2.hideCoverage()) self.assertEqual(atlas2.filenameExpression(), 'filename exp') self.assertEqual(atlas2.coverageLayer(), vector_layer) self.assertEqual(atlas2.pageNameExpression(), 'page name') self.assertTrue(atlas2.sortFeatures()) self.assertFalse(atlas2.sortAscending()) self.assertEqual(atlas2.sortExpression(), 'sort exp') self.assertTrue(atlas2.filterFeatures()) self.assertEqual(atlas2.filterExpression(), 'filter exp')
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 testRasterDemProvider(self): """ Test QgsRasterDemTerrainProvider """ provider = QgsRasterDemTerrainProvider() self.assertEqual(provider.type(), 'raster') # without layer assigned self.assertFalse(provider.crs().isValid()) self.assertTrue(math.isnan(provider.heightAt(1, 2))) # add raster layer to project p = QgsProject() rl = QgsRasterLayer(os.path.join(unitTestDataPath(), 'float1-16.tif'), 'rl') self.assertTrue(rl.isValid()) p.addMapLayer(rl) provider.setLayer(rl) self.assertEqual(provider.layer(), rl) self.assertEqual(provider.crs().authid(), 'EPSG:4326') self.assertEqual(provider.heightAt(106.4105, -6.6341), 11.0) # outside of raster extent self.assertTrue(math.isnan(provider.heightAt(1, 2))) provider.setOffset(5) self.assertEqual(provider.offset(), 5) provider.setScale(3) self.assertEqual(provider.scale(), 3) self.assertEqual(provider.heightAt(106.4105, -6.6341), 11 * 3 + 5) clone = provider.clone() self.assertIsInstance(clone, QgsRasterDemTerrainProvider) self.assertEqual(clone.layer(), rl) self.assertEqual(clone.offset(), 5) self.assertEqual(clone.scale(), 3) # via xml doc = QDomDocument("testdoc") context = QgsReadWriteContext() parent_elem = doc.createElement('test') element = provider.writeXml(doc, context) parent_elem.appendChild(element) from_xml = QgsRasterDemTerrainProvider() self.assertTrue(from_xml.readXml(parent_elem, context)) self.assertEqual(from_xml.offset(), 5) self.assertEqual(from_xml.scale(), 3) # layer won't be resolved till we resolve references from project self.assertFalse(from_xml.layer()) from_xml.resolveReferences(p) self.assertEqual(from_xml.layer(), rl) # test equals provider1 = QgsRasterDemTerrainProvider() provider2 = QgsRasterDemTerrainProvider() self.assertTrue(provider1.equals(provider2)) self.assertFalse(provider1.equals(QgsFlatTerrainProvider())) provider1.setOffset(1) self.assertFalse(provider1.equals(provider2)) provider2.setOffset(1) self.assertTrue(provider1.equals(provider2)) provider1.setScale(11) self.assertFalse(provider1.equals(provider2)) provider2.setScale(11) self.assertTrue(provider1.equals(provider2)) provider1.setLayer(rl) self.assertFalse(provider1.equals(provider2)) provider2.setLayer(rl) self.assertTrue(provider1.equals(provider2))
def testIteration(self): p = QgsProject() vectorFileInfo = QFileInfo(unitTestDataPath() + "/france_parts.shp") vector_layer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr") self.assertTrue(vector_layer.isValid()) p.addMapLayer(vector_layer) l = QgsPrintLayout(p) atlas = l.atlas() atlas.setEnabled(True) atlas.setCoverageLayer(vector_layer) atlas_feature_changed_spy = QSignalSpy(atlas.featureChanged) context_changed_spy = QSignalSpy(l.reportContext().changed) self.assertTrue(atlas.beginRender()) self.assertTrue(atlas.first()) self.assertEqual(len(atlas_feature_changed_spy), 1) self.assertEqual(len(context_changed_spy), 1) self.assertEqual(atlas.currentFeatureNumber(), 0) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') self.assertEqual(l.reportContext().layer(), vector_layer) f1 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 2) self.assertEqual(len(context_changed_spy), 2) self.assertEqual(atlas.currentFeatureNumber(), 1) self.assertEqual(l.reportContext().feature()[4], 'Bretagne') f2 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 3) self.assertEqual(len(context_changed_spy), 3) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') f3 = l.reportContext().feature() self.assertTrue(atlas.next()) self.assertEqual(len(atlas_feature_changed_spy), 4) self.assertEqual(len(context_changed_spy), 4) self.assertEqual(atlas.currentFeatureNumber(), 3) self.assertEqual(l.reportContext().feature()[4], 'Centre') f4 = l.reportContext().feature() self.assertFalse(atlas.next()) self.assertTrue(atlas.seekTo(2)) self.assertEqual(len(atlas_feature_changed_spy), 5) self.assertEqual(len(context_changed_spy), 5) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.last()) self.assertEqual(len(atlas_feature_changed_spy), 6) self.assertEqual(len(context_changed_spy), 6) self.assertEqual(atlas.currentFeatureNumber(), 3) self.assertEqual(l.reportContext().feature()[4], 'Centre') self.assertTrue(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 7) self.assertEqual(len(context_changed_spy), 7) self.assertEqual(atlas.currentFeatureNumber(), 2) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.previous()) self.assertTrue(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 9) self.assertFalse(atlas.previous()) self.assertEqual(len(atlas_feature_changed_spy), 9) self.assertTrue(atlas.endRender()) self.assertEqual(len(atlas_feature_changed_spy), 10) self.assertTrue(atlas.seekTo(f1)) self.assertEqual(l.reportContext().feature()[4], 'Basse-Normandie') self.assertTrue(atlas.seekTo(f4)) self.assertEqual(l.reportContext().feature()[4], 'Centre') self.assertTrue(atlas.seekTo(f3)) self.assertEqual(l.reportContext().feature()[4], 'Pays de la Loire') self.assertTrue(atlas.seekTo(f2)) self.assertEqual(l.reportContext().feature()[4], 'Bretagne') self.assertFalse(atlas.seekTo(QgsFeature(5)))
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 testMeshProvider(self): """ Test QgsMeshTerrainProvider """ provider = QgsMeshTerrainProvider() self.assertEqual(provider.type(), 'mesh') # without layer assigned self.assertFalse(provider.crs().isValid()) self.assertTrue(math.isnan(provider.heightAt(1, 2))) # add mesh layer to project p = QgsProject() mesh_layer = QgsMeshLayer( os.path.join(unitTestDataPath(), '3d', 'elev_mesh.2dm'), 'mdal', 'mdal') mesh_layer.setCrs(QgsCoordinateReferenceSystem('EPSG:27700')) self.assertTrue(mesh_layer.isValid()) p.addMapLayer(mesh_layer) provider.setLayer(mesh_layer) self.assertEqual(provider.layer(), mesh_layer) self.assertEqual(provider.crs().authid(), 'EPSG:27700') self.assertTrue(math.isnan(provider.heightAt(1, 2))) self.assertAlmostEqual(provider.heightAt(321695.2, 129990.5), 89.49743150684921, 5) provider.setOffset(5) self.assertEqual(provider.offset(), 5) provider.setScale(3) self.assertEqual(provider.scale(), 3) clone = provider.clone() self.assertIsInstance(clone, QgsMeshTerrainProvider) self.assertEqual(clone.layer(), mesh_layer) self.assertEqual(clone.offset(), 5) self.assertEqual(clone.scale(), 3) # via xml doc = QDomDocument("testdoc") context = QgsReadWriteContext() parent_elem = doc.createElement('test') element = provider.writeXml(doc, context) parent_elem.appendChild(element) from_xml = QgsMeshTerrainProvider() self.assertTrue(from_xml.readXml(parent_elem, context)) self.assertEqual(from_xml.offset(), 5) self.assertEqual(from_xml.scale(), 3) # layer won't be resolved till we resolve references from project self.assertFalse(from_xml.layer()) from_xml.resolveReferences(p) self.assertEqual(from_xml.layer(), mesh_layer) # test equals provider1 = QgsMeshTerrainProvider() provider2 = QgsMeshTerrainProvider() self.assertTrue(provider1.equals(provider2)) self.assertFalse(provider1.equals(QgsFlatTerrainProvider())) provider1.setOffset(1) self.assertFalse(provider1.equals(provider2)) provider2.setOffset(1) self.assertTrue(provider1.equals(provider2)) provider1.setScale(11) self.assertFalse(provider1.equals(provider2)) provider2.setScale(11) self.assertTrue(provider1.equals(provider2)) provider1.setLayer(mesh_layer) self.assertFalse(provider1.equals(provider2)) provider2.setLayer(mesh_layer) self.assertTrue(provider1.equals(provider2))
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 testSaveLoadProject(self): schema_uri = encode_uri(self.ds_uri, 'qgis_test') project_uri = encode_uri(self.ds_uri, 'qgis_test', 'abc') self.dropProjectsTable() # make sure we have a clean start prj = QgsProject() uri = self.vl.source() vl1 = QgsVectorLayer(uri, 'test', 'postgres') self.assertEqual(vl1.isValid(), True) prj.addMapLayer(vl1) prj_storage = QgsApplication.projectStorageRegistry( ).projectStorageFromType("postgresql") self.assertTrue(prj_storage) lst0 = prj_storage.listProjects(schema_uri) self.assertEqual(lst0, []) # try to save project in the database prj.setFileName(project_uri) res = prj.write() self.assertTrue(res) lst1 = prj_storage.listProjects(schema_uri) self.assertEqual(lst1, ["abc"]) # now try to load the project back prj2 = QgsProject() prj2.setFileName(project_uri) res = prj2.read() self.assertTrue(res) self.assertEqual(len(prj2.mapLayers()), 1) self.assertEqual(prj2.baseName(), "abc") self.assertEqual(prj2.absoluteFilePath(), "") # path not supported for project storages self.assertTrue( abs(prj2.lastModified().secsTo(QDateTime.currentDateTime())) < 10) # try to see project's metadata res, metadata = prj_storage.readProjectStorageMetadata(project_uri) self.assertTrue(res) self.assertEqual(metadata.name, "abc") time_project = metadata.lastModified time_now = QDateTime.currentDateTime() time_diff = time_now.secsTo(time_project) self.assertTrue(abs(time_diff) < 10) # try to remove the project res = prj_storage.removeProject(project_uri) self.assertTrue(res) lst2 = prj_storage.listProjects(schema_uri) self.assertEqual(lst2, []) self.dropProjectsTable( ) # make sure we have a clean finish... "leave no trace"
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 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 test_nested_groups(self): """ Test logic relating to nested groups with group layers """ p = QgsProject() layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") p.addMapLayer(layer, False) layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2", "memory") p.addMapLayer(layer2, False) layer3 = QgsVectorLayer("Point?field=fldtxt:string", "layer3", "memory") p.addMapLayer(layer3, False) layer4 = QgsVectorLayer("Point?field=fldtxt:string", "layer4", "memory") p.addMapLayer(layer4, False) group_node = p.layerTreeRoot().addGroup('my group') group_node.addLayer(layer) group_node.addLayer(layer2) child_group = group_node.addGroup('child') layer3_node = child_group.addLayer(layer3) grandchild_group = child_group.addGroup('grandchild') layer4_node = grandchild_group.addLayer(layer4) self.assertEqual(p.layerTreeRoot().layerOrder(), [layer, layer2, layer3, layer4]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [layer, layer2, layer3, layer4]) spy = QSignalSpy(p.layerTreeRoot().layerOrderChanged) options = QgsGroupLayer.LayerOptions(QgsCoordinateTransformContext()) group_layer = group_node.convertToGroupLayer(options) p.addMapLayer(group_layer, False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [layer4, layer3, layer2, layer]) spy_count = len(spy) self.assertEqual(spy_count, 1) grandchild_group_layer = grandchild_group.convertToGroupLayer(options) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [grandchild_group_layer, layer3, layer2, layer]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer4_node.setItemVisibilityChecked(False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [grandchild_group_layer, layer3, layer2, layer]) self.assertEqual(grandchild_group_layer.childLayers(), []) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer4_node.setItemVisibilityChecked(True) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [grandchild_group_layer, layer3, layer2, layer]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) grandchild_group.setItemVisibilityChecked(False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [layer3, layer2, layer]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) grandchild_group.setItemVisibilityChecked(True) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [grandchild_group_layer, layer3, layer2, layer]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) child_group_layer = child_group.convertToGroupLayer(options) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer, layer3]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer4_node.setItemVisibilityChecked(False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer, layer3]) self.assertEqual(grandchild_group_layer.childLayers(), []) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer4_node.setItemVisibilityChecked(True) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer, layer3]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) grandchild_group.setItemVisibilityChecked(False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [layer3]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) grandchild_group.setItemVisibilityChecked(True) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer, layer3]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer3_node.setItemVisibilityChecked(False) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) layer3_node.setItemVisibilityChecked(True) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [grandchild_group_layer, layer3]) self.assertEqual(grandchild_group_layer.childLayers(), [layer4]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) grandchild_group.setGroupLayer(None) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [child_group_layer, layer2, layer]) self.assertEqual(child_group_layer.childLayers(), [layer4, layer3]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) child_group.setGroupLayer(None) self.assertEqual(p.layerTreeRoot().layerOrder(), [group_layer]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [group_layer]) self.assertEqual(group_layer.childLayers(), [layer4, layer3, layer2, layer]) self.assertGreater(len(spy), spy_count) spy_count = len(spy) group_node.setGroupLayer(None) self.assertEqual(p.layerTreeRoot().layerOrder(), [layer, layer2, layer3, layer4]) self.assertEqual(p.layerTreeRoot().checkedLayers(), [layer, layer2, layer3, layer4]) self.assertGreater(len(spy), spy_count)
def processAlgorithm(self, parameters, context, feedback): project = QgsProject() project.setFileName( os.path.join(parameters[self.FOLDER], "all-outputs-qgis.qgs")) project.setCrs(QgsCoordinateReferenceSystem('EPSG:27700')) def getMaxValue(layer, fieldname): maxfound = float("-inf") for f in layer.getFeatures(): attr = f.attribute(fieldname) assert attr >= 0 if attr > maxfound: maxfound = attr return maxfound with open( os.path.join(parameters[self.FOLDER], "all-town-metadata.json")) as f: metadata = json.load(f) classmethods = { 'quantile': QgsClassificationQuantile, 'jenks': QgsClassificationJenks, 'equal': QgsClassificationEqualInterval } html = "" output = [] views_sorted_by_mode = sorted(metadata["views"], key=lambda v: v["mode"]) for view in views_sorted_by_mode: keysymbol = u'🔑' viewname = view["label"] keysign = "" if viewname.find(keysymbol) != -1: viewname = viewname.replace(keysymbol, '', 1) keysign = "*** " viewname = keysign + view["mode"] + " " + viewname html += f""" <h2>{viewname}</h2> {view["description"]} <ul> """ for layer in view["layers"]: layername = viewname + " - " + layer["scalar_field_units"] layerpath = os.path.join(parameters[self.FOLDER], layer["file"]) vlayer = QgsVectorLayer(layerpath, layername, "ogr") if not vlayer.isValid(): feedback.pushInfo("Layer failed to load: " + layerpath) else: context.temporaryLayerStore().addMapLayer(vlayer) html += f"""<li><b>file:</b> {layer["file"]}""" if "symbol_field" in layer: html += f"""<ul> <li><b>symbol field:</b> {layer["symbol_field"]} </ul> """ categories = [] scalar_fieldname = layer["scalar_field"] maxvalue = getMaxValue(vlayer, scalar_fieldname) feedback.pushInfo("Max value for %s is %f" % (scalar_fieldname, maxvalue)) for formality in ["I", "F"]: for severity, colour in [(3, 'red'), (2, 'yellow'), (1, 'green')]: colour = { ("I", "red"): "#FF0000", ("I", "yellow"): "#FFFF00", ("I", "green"): "#00FF00", ("F", "red"): "#FF9999", ("F", "yellow"): "#FFFF66", ("F", "green"): "#99FF99", }[(formality, colour)] symbol_code = "%s%d" % (formality, severity) if formality == "F": symbol = QgsMarkerSymbol.createSimple({ 'color': colour, 'size': '3', 'outline_color': '#888888' }) else: assert (formality == "I") symbol = QgsMarkerSymbol.createSimple({ 'color': colour, 'size': '3', 'outline_color': '#000000', 'name': 'star' }) objTransf = QgsSizeScaleTransformer( QgsSizeScaleTransformer.Flannery, 0, #minvalue maxvalue, #maxvalue 3, #minsize 10, #maxsize 0, #nullsize 1) #exponent objProp = QgsProperty() objProp.setField(scalar_fieldname) objProp.setTransformer(objTransf) symbol.setDataDefinedSize(objProp) label = { "F": "Formal", "I": "Informal" }[formality] + " " + { 3: "Major", 2: "Secondary", 1: "Tertiary" }[severity] cat = QgsRendererCategory( symbol_code, symbol, label, True) categories.append(cat) renderer = QgsCategorizedSymbolRenderer( "Crossings", categories) renderer.setClassAttribute(layer["symbol_field"]) vlayer.setRenderer(renderer) else: html += f"""<ul> <li><b>field:</b> {layer["scalar_field"]} <li><b>units:</b> {layer["scalar_field_units"]} <li><b>recommended classification:</b> {layer["classes"]} </ul> """ default_style = QgsStyle().defaultStyle() color_ramp = default_style.colorRamp('bt') renderer = QgsGraduatedSymbolRenderer() renderer.setClassAttribute(layer["scalar_field"]) classmethod = classmethods[layer["classes"]]() renderer.setClassificationMethod(classmethod) renderer.updateClasses(vlayer, 5) renderer.updateColorRamp(color_ramp) vlayer.setRenderer(renderer) project.addMapLayer(vlayer) feedback.pushInfo("Loaded " + layerpath) html += "</ul>" project.write() town = views_sorted_by_mode[0]["town"] with open(os.path.join(parameters[self.FOLDER], "metadata.html"), "w") as htmlfile: htmlfile.write( f"<html><head><title>{town} metadata</title></head><body><h1>{town}</h1>{html}</body></html>" ) return {self.OUTPUT: output}
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)