def test_AddPALToVectorLayer(self): """Check if we can set a label field, verify that PAL is assigned and that output is rendered correctly""" # TODO: add UTM PAL-specific shps, with 4326 as on-the-fly cross-check # setCanvasCrs(26913) myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') myVectorLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self._MapRegistry.addMapLayer(myVectorLayer) myLayers = QStringList() myLayers.append(myVectorLayer.id()) self._MapRenderer.setLayerSet(myLayers) self._MapRenderer.setExtent(myVectorLayer.extent()) self._Canvas.zoomToFullExtent() # check layer labeling is PAL with customProperty access # should not be activated on layer load myPalSet = myVectorLayer.customProperty( "labeling" ).toString() myMessage = '\nExpected: Empty QString\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == '', myMessage # simulate clicking checkbox, setting label field and clicking apply self._testFont.setPointSize(20) myPalLyr = QgsPalLayerSettings() myPalLyr.enabled = True myPalLyr.fieldName = 'Name' myPalLyr.placement = QgsPalLayerSettings.Line myPalLyr.placementFlags = QgsPalLayerSettings.AboveLine myPalLyr.xQuadOffset = 0 myPalLyr.yQuadOffset = 0 myPalLyr.xOffset = 0 myPalLyr.yOffset = 0 myPalLyr.angleOffset = 0 myPalLyr.centroidWhole = False myPalLyr.textFont = self._testFont myPalLyr.textNamedStyle = QString("Medium") myPalLyr.textColor = Qt.black myPalLyr.textTransp = 0 myPalLyr.previewBkgrdColor = Qt.white myPalLyr.priority = 5 myPalLyr.obstacle = True myPalLyr.dist = 0 myPalLyr.scaleMin = 0 myPalLyr.scaleMax = 0 myPalLyr.bufferSize = 1 myPalLyr.bufferColor = Qt.white myPalLyr.bufferTransp = 0 myPalLyr.bufferNoFill = False myPalLyr.bufferJoinStyle = Qt.RoundJoin myPalLyr.formatNumbers = False myPalLyr.decimals = 3 myPalLyr.plusSign = False myPalLyr.labelPerPart = False myPalLyr.displayAll = True myPalLyr.mergeLines = False myPalLyr.minFeatureSize = 0.0 myPalLyr.vectorScaleFactor = 1.0 myPalLyr.rasterCompressFactor = 1.0 myPalLyr.addDirectionSymbol = False myPalLyr.upsidedownLabels = QgsPalLayerSettings.Upright myPalLyr.fontSizeInMapUnits = False myPalLyr.bufferSizeInMapUnits = False myPalLyr.labelOffsetInMapUnits = True myPalLyr.distInMapUnits = False myPalLyr.wrapChar = "" myPalLyr.preserveRotation = True myPalLyr.writeToLayer(myVectorLayer) # check layer labeling is PAL with customProperty access myPalSet = myVectorLayer.customProperty( "labeling" ).toString() myMessage = '\nExpected: pal\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == 'pal', myMessage # check layer labeling is PAL via engine interface myMessage = '\nCould not get whether PAL enabled from labelingEngine' assert self._PalEngine.willUseLayer(myVectorLayer), myMessage # myChecker = QgsRenderChecker() myChecker.setControlName("expected_pal_aboveLineLabeling") myChecker.setMapRenderer(self._MapRenderer) myResult = myChecker.runTest("pal_aboveLineLabeling_python"); myMessage = ('\nVector layer \'above line\' label engine ' 'rendering test failed') assert myResult, myMessage # compare against a straight rendering/save as from QgsMapCanvasMap # unnecessary? works a bit different than QgsRenderChecker, though # myImage = os.path.join(unicode(QDir.tempPath()), # 'render_pal_aboveLineLabeling.png') # self._Map.render() # self._Canvas.saveAsImage(myImage) # myChecker.setRenderedImage(myImage) # myResult = myChecker.compareImages("pal_aboveLineLabeling_python") # myMessage = ('\nVector layer \'above line\' label engine ' # 'comparison to QgsMapCanvasMap.render() test failed') # assert myResult, myMessage self._MapRegistry.removeMapLayer(myVectorLayer.id())
def save_adres_point(self, point, address, typeAddress='', layername="Geopunt_adres", saveToFile=False, sender=None, startFolder=None ): attributes = [QgsField("adres", QVariant.String), QgsField("type", QVariant.String)] mapcrs = self.getGetMapCrs(self.iface) if not QgsProject.instance().mapLayer(self.adreslayerid): self.adreslayer = QgsVectorLayer("Point", layername, "memory") self.adresProvider = self.adreslayer.dataProvider() self.adresProvider.addAttributes(attributes) self.adreslayer.updateFields() # add a feature fields= self.adreslayer.fields() fet = QgsFeature(fields) #set geometry and project from mapCRS xform = QgsCoordinateTransform( mapcrs, self.adreslayer.crs(), QgsProject.instance() ) prjPoint = xform.transform( point ) fet.setGeometry(QgsGeometry.fromPointXY(prjPoint)) #populate fields fet['adres'] = address fet['type'] = typeAddress self.adresProvider.addFeatures([ fet ]) "" # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer self.adreslayer.updateExtents() # save memoryLAYER to file and replace all references if saveToFile and not QgsProject.instance().mapLayer(self.adreslayerid): save = self._saveToFile( sender, startFolder ) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat(self.adreslayer, fileName=fpath, fileEncoding="utf-8", driverName=flType) if error == QgsVectorFileWriter.NoError: self.adreslayer = QgsVectorLayer( fpath, layername, "ogr") self.adresProvider = self.adreslayer.dataProvider() else: del self.adreslayer, self.adresProvider return else: del self.adreslayer, self.adresProvider return # add to map QgsProject.instance().addMapLayer(self.adreslayer) #labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'adres' palyr.placement = QgsPalLayerSettings.Free self.adreslayer.setLabelsEnabled(True) self.adreslayer.setLabeling( QgsVectorLayerSimpleLabeling(palyr) ) # store layer id and refresh self.adreslayerid = self.adreslayer.id() self.canvas.refresh()
def prepare_ordered_marker(self, coords, idx): """ Try to display nice marker on a point layer, showing the order of the path computed by OSRM. """ self.tsp_marker_lr = QgsVectorLayer( "Point?crs=epsg:4326&field=id:integer" "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)", "tsp_markers_osrm{}".format(self.nb_route), "memory") symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType()) symbol.setSize(4.5) symbol.setColor(QtGui.QColor("yellow")) ordered_pts = \ [coords[i["waypoint_index"]] for i in self.parsed['waypoints']] print("ordered_pts : ", ordered_pts) features = [] for nb, pt in enumerate(ordered_pts): ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt))) ft.setAttributes([nb, nb + 1, coords.index(pt)]) features.append(ft) self.tsp_marker_lr.dataProvider().addFeatures(features) pal_lyr = QgsPalLayerSettings() pal_lyr.readFromLayer(self.tsp_marker_lr) pal_lyr.enabled = True pal_lyr.fieldName = 'TSP_nb' pal_lyr.placement= QgsPalLayerSettings.OverPoint pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'12','') pal_lyr.writeToLayer(self.tsp_marker_lr) self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol)) QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
def test_settings_enable_pal(self): # Verify default PAL settings enable PAL labeling for layer lyr = QgsPalLayerSettings() lyr.writeToLayer(self.layer) palset = self.layer.customProperty('labeling', '') msg = '\nExpected: Empty string\nGot: {0}'.format(palset) self.assertEqual(palset, 'pal', msg)
def test_settings_enable_pal(self): # Verify default PAL settings enable PAL labeling for layer lyr = QgsPalLayerSettings() lyr.writeToLayer(self.layer) palset = self.layer.customProperty("labeling", "").toString() msg = "\nExpected: Empty string\nGot: {0}".format(palset) self.assertEqual(palset, "pal", msg)
def defaultSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in data sources lyr.textFont = self._TestFont lyr.textNamedStyle = 'Medium' return lyr
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = "text" # default in test data sources font = self.getTestFont() font.setPointSize(32) lyr.textFont = font lyr.textNamedStyle = "Roman" return lyr
def defaultSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in data sources font = self.getTestFont() font.setPointSize(48) lyr.textFont = font lyr.textNamedStyle = 'Roman' return lyr
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.fieldName = 'text' # default in test data sources font = self.getTestFont() font.setPointSize(32) format = lyr.format() format.setFont(font) format.setNamedStyle('Roman') format.setSize(32) format.setSizeUnit(QgsUnitTypes.RenderPoints) format.buffer().setJoinStyle(Qt.BevelJoin) lyr.setFormat(format) return lyr
def test_write_read_settings(self): # Verify written PAL settings are same when read from layer # load and write default test settings lyr1 = self.defaultLayerSettings() lyr1dict = self.settingsDict(lyr1) # print lyr1dict lyr1.writeToLayer(self.layer) # read settings lyr2 = QgsPalLayerSettings() lyr2.readFromLayer(self.layer) lyr2dict = self.settingsDict(lyr1) # print lyr2dict msg = '\nLayer settings read not same as settings written' self.assertDictEqual(lyr1dict, lyr2dict, msg)
def checkRemovingLabeledLayerInvalidatesLabelCache(self, job_type): """ removing a previously labeled layer should invalidate any previous label caches""" layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") labelSettings = QgsPalLayerSettings() labelSettings.fieldName = "fldtxt" layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings)) layer.setLabelsEnabled(True) layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2", "memory") layer2.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings)) layer2.setLabelsEnabled(True) settings = QgsMapSettings() settings.setExtent(QgsRectangle(5, 25, 25, 45)) settings.setOutputSize(QSize(600, 400)) settings.setLayers([layer, layer2]) # with cache - first run should populate cache cache = QgsMapRendererCache() job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() self.assertFalse(job.usedCachedLabels()) self.assertTrue(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults()) self.assertEqual(set(cache.dependentLayers('_labels_')), {layer, layer2}) # remove a previously labeled layer settings.setLayers([layer2]) # second job should not be able to use label cache, since a labeled layer was removed job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() # shouldn't use cache self.assertFalse(job.usedCachedLabels()) # but results should have been cached self.assertTrue(cache.hasCacheImage('_labels_')) self.assertEqual(set(cache.dependentLayers('_labels_')), {layer2}) self.assertTrue(job.takeLabelingResults())
def checkAddingNewNonLabeledLayerKeepsLabelCache(self, job_type): """ adding a new non-labeled layer should keep any previous label caches""" layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") labelSettings = QgsPalLayerSettings() labelSettings.fieldName = "fldtxt" layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings)) layer.setLabelsEnabled(True) settings = QgsMapSettings() settings.setExtent(QgsRectangle(5, 25, 25, 45)) settings.setOutputSize(QSize(600, 400)) settings.setLayers([layer]) # with cache - first run should populate cache cache = QgsMapRendererCache() job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() self.assertFalse(job.usedCachedLabels()) self.assertTrue(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults()) self.assertEqual(cache.dependentLayers('_labels_'), [layer]) # add another, non-labeled layer layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2", "memory") settings.setLayers([layer, layer2]) # second job should use label cache, since new layer was not labeled job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() # should use cache self.assertTrue(job.usedCachedLabels()) # results should have been cached self.assertTrue(cache.hasCacheImage('_labels_')) self.assertEqual(set(cache.dependentLayers('_labels_')), {layer}) self.assertTrue(job.takeLabelingResults())
def remove_mask_filter(layer): if not isinstance(layer, QgsVectorLayer): return False # check if a layer has already a mask filter enabled if layer.labeling() is None: return False settings = layer.labeling().settings() try: if settings.dataDefinedProperties().hasProperty(QgsPalLayerSettings.Show) and \ settings.dataDefinedProperties().property(QgsPalLayerSettings.Show).expressionString().startswith(SPATIAL_FILTER): # new settings settings = QgsPalLayerSettings(layer.labeling().settings()) settings.dataDefinedProperties().setProperty(QgsPalLayerSettings.Show, True) if isinstance(layer.labeling(), QgsVectorLayerSimpleLabeling): layer.setLabeling(QgsVectorLayerSimpleLabeling(settings)) except Exception as e: for m in e.args: QgsMessageLog.logMessage(m, 'Extensions')
def checkRepaintLabeledLayerInvalidatesLabelCache(self, job_type): layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") labelSettings = QgsPalLayerSettings() labelSettings.fieldName = "fldtxt" layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings)) layer.setLabelsEnabled(True) settings = QgsMapSettings() settings.setExtent(QgsRectangle(5, 25, 25, 45)) settings.setOutputSize(QSize(600, 400)) settings.setLayers([layer]) # with cache - first run should populate cache cache = QgsMapRendererCache() job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() self.assertFalse(job.usedCachedLabels()) self.assertTrue(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults()) self.assertEqual(cache.dependentLayers('_labels_'), [layer]) # trigger repaint on layer - should invalidate cache and block use of cached labels layer.triggerRepaint() self.assertFalse(cache.hasCacheImage('_labels_')) # second job should not use label cache, since layer was repainted job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() # shouldn't use cache self.assertFalse(job.usedCachedLabels()) # but results should have been cached self.assertTrue(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults())
def createLayer(self): '''Create a memory layer from the zoom to locations''' rowcnt = self.resultsTable.rowCount() if rowcnt == 0: return attr = [] for item, label in enumerate(LABELS[0:self.numCol]): label = label.lower() if item <= 1: attr.append(QgsField(label, QVariant.Double)) else: attr.append(QgsField(label, QVariant.String)) ptLayer = QgsVectorLayer("Point?crs=epsg:4326", u"Lat Lon Locations", "memory") provider = ptLayer.dataProvider() provider.addAttributes(attr) ptLayer.updateFields() for id in range(rowcnt): item = self.resultsTable.item(id, 0).data(Qt.UserRole) feature = QgsFeature() feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(item.lon, item.lat))) attr = [item.lat, item.lon, item.label] for i in range(3, self.numCol): attr.append(item.data[i-3]) feature.setAttributes(attr) provider.addFeatures([feature]) ptLayer.updateExtents() if self.settings.multiZoomStyleID == 1: settings = QgsPalLayerSettings() settings.fieldName = 'label' settings.placement = QgsPalLayerSettings.AroundPoint labeling = QgsVectorLayerSimpleLabeling(settings) ptLayer.setLabeling(labeling) ptLayer.setLabelsEnabled(True) elif self.settings.multiZoomStyleID == 2 and os.path.isfile(self.settings.customQMLFile()): ptLayer.loadNamedStyle(self.settings.customQMLFile()) QgsProject.instance().addMapLayer(ptLayer)
def add_mask_filter(layer): if not isinstance(layer, QgsVectorLayer): return False # check if a layer has already a mask filter enabled if layer.labeling() is None: return False try: expr = "%s(%d)" % (SPATIAL_FILTER, layer.crs().postgisSrid()) prop = QgsProperty() prop.setExpressionString(expr) # new settings settings = QgsPalLayerSettings(layer.labeling().settings()) settings.dataDefinedProperties().setProperty(QgsPalLayerSettings.Show, prop) if isinstance(layer.labeling(), QgsVectorLayerSimpleLabeling): layer.setLabeling(QgsVectorLayerSimpleLabeling(settings)) except Exception as e: for m in e.args: QgsMessageLog.logMessage(m, 'Extensions')
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in test data sources font = self.getTestFont() font.setPointSize(32) lyr.textFont = font lyr.textNamedStyle = 'Roman' lyr.bufferJoinStyle = Qt.BevelJoin # handle change of default join style return lyr
def __init__(self): """Dummy assignments, intended to be overridden in subclasses""" self.lyr = QgsPalLayerSettings() """:type: QgsPalLayerSettings""" # noinspection PyArgumentList self._TestFont = QFont() # will become a standard test font self._Canvas = None """:type: QgsMapCanvas""" # custom mismatches per group/test (should not mask any needed anomaly) # e.g. self._Mismatches['TestClassName'] = 300 # check base output class's checkTest() or sublcasses for any defaults self._Mismatches = dict() # custom color tolerances per group/test: 1 - 20 (0 default, 20 max) # (should not mask any needed anomaly) # e.g. self._ColorTols['TestClassName'] = 10 # check base output class's checkTest() or sublcasses for any defaults self._ColorTols = dict()
def checkLabeledLayerWithBlendModesCannotBeCached(self, job_type): """ any labeled layer utilising blending modes cannot be cached""" layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory") labelSettings = QgsPalLayerSettings() labelSettings.fieldName = "fldtxt" layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings)) layer.setLabelsEnabled(True) layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2", "memory") labelSettings2 = QgsPalLayerSettings() labelSettings2.fieldName = "fldtxt" format2 = QgsTextFormat() format2.setBlendMode(QPainter.CompositionMode_SourceIn) labelSettings2.setFormat(format2) layer2.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings2)) layer2.setLabelsEnabled(True) settings = QgsMapSettings() settings.setExtent(QgsRectangle(5, 25, 25, 45)) settings.setOutputSize(QSize(600, 400)) settings.setLayers([layer, layer2]) # with cache - cache should not be populated! cache = QgsMapRendererCache() job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() self.assertFalse(job.usedCachedLabels()) self.assertFalse(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults()) # second job should also not be able to use label cache job = job_type(settings) job.setCache(cache) job.start() job.waitForFinished() # shouldn't use cache self.assertFalse(job.usedCachedLabels()) # and results should not have been cached self.assertFalse(cache.hasCacheImage('_labels_')) self.assertTrue(job.takeLabelingResults())
def testCreateProperty(self): s = QgsAuxiliaryStorage() self.assertTrue(s.isValid()) # Create a new auxiliary layer with 'pk' as key vl = createLayer() pkf = vl.fields().field(vl.fields().indexOf('pk')) al = s.createAuxiliaryLayer(pkf, vl) self.assertTrue(al.isValid()) vl.setAuxiliaryLayer(al) # Create a new labeling property on layer without labels key = QgsPalLayerSettings.PositionX index = QgsAuxiliaryLayer.createProperty(key, vl) self.assertEqual(index, -1) vl.setLabeling(QgsVectorLayerSimpleLabeling(QgsPalLayerSettings())) index = QgsAuxiliaryLayer.createProperty(key, vl) p = QgsPalLayerSettings.propertyDefinitions()[key] afName = QgsAuxiliaryLayer.nameFromProperty(p, True) afIndex = vl.fields().indexOf(afName) self.assertEqual(index, afIndex)
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 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 testAuxiliaryFieldWidgets(self): # Init storage s = QgsAuxiliaryStorage() self.assertTrue(s.isValid()) # Create a new auxiliary layer with 'pk' as key vl = createLayer() pkf = vl.fields().field(vl.fields().indexOf('pk')) al = s.createAuxiliaryLayer(pkf, vl) self.assertTrue(al.isValid()) # Set the auxiliary layer to the vector layer vl.setAuxiliaryLayer(al) # Add a visible property p = QgsPropertyDefinition('propName', QgsPropertyDefinition.DataTypeNumeric, '', '', 'user') self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertFalse(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), '') tested = False for c in vl.attributeTableConfig().columns(): if c.name == afName: self.assertFalse(c.hidden) tested = True break self.assertTrue(tested) # Add a hidden property p = QgsPalLayerSettings.propertyDefinitions()[QgsPalLayerSettings.PositionX] self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertTrue(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), 'Hidden') tested = False for c in vl.attributeTableConfig().columns(): if c.name == afName: self.assertTrue(c.hidden) tested = True break self.assertTrue(tested) # Add a color property p = QgsSymbolLayer.propertyDefinitions()[QgsSymbolLayer.PropertyFillColor] self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertFalse(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), 'Color')
def utmGridlabelPlacer(self, root_rule, grid_spacing, geo_bound_bb, bound_UTM_bb, geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0, dy1, fSize, fontType, scale, utmcheck, geo_bb_or): xmin_source = float(geo_bound_bb.split()[1]) ymin_source = float(geo_bound_bb.split()[2]) xmax_source = float(geo_bound_bb.split()[3]) ymax_source = float(geo_bound_bb.split()[4]) xmin_UTM = float(bound_UTM_bb.split()[1]) ymin_UTM = float(bound_UTM_bb.split()[2]) xmax_UTM = float(bound_UTM_bb.split()[3]) ymax_UTM = float(bound_UTM_bb.split()[4]) px = (xmax_source - xmin_source) / (geo_number_x + 1) py = (ymax_source - ymin_source) / (geo_number_y + 1) if grid_spacing > 0: # Bottom ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings()) ruletest = self.utm_grid_labeler( ruletest, xmin_UTM, ymin_UTM, 0, ymin_source, px, py, trUTMLL, trLLUTM, 1, True, 0, dy[1] + 0.4 * (scale) * fSize / 1.5, dy0[1] + 0.4 * (scale) * fSize / 1.5, 0, 'Top', 'Center', 'UTMBotTest', fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, range(1), geo_bb_or) rulechild = ruletest.children()[0] if rulechild.settings().fieldName == 'fail': rangeUD = range(2, UTM_num_x + 1) else: rangeUD = range(1, UTM_num_x + 1) for u in rangeUD: root_rule = self.utm_grid_labeler( root_rule, xmin_UTM, ymin_UTM, 0, ymin_source, px, py, trUTMLL, trLLUTM, u, True, 0, dy[1] + 0.4 * (scale) * fSize / 1.5, dy0[1] + 0.4 * (scale) * fSize / 1.5, 0, 'Top', 'Center', 'UTMBot' + str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeUD, geo_bb_or) # Upper rangeUD = range(1, UTM_num_x + 1) for u in rangeUD: root_rule = self.utm_grid_labeler( root_rule, xmin_UTM, ymax_UTM, 0, ymax_source, px, py, trUTMLL, trLLUTM, u, True, 0, dy[0] - 1.3 * (scale) * fSize / 1.5, dy0[0] - 1.3 * (scale) * fSize / 1.5, 0, 'Bottom', 'Center', 'UTMUp' + str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeUD, geo_bb_or) # Left ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings()) ruletest = self.utm_grid_labeler( ruletest, xmin_UTM, ymin_UTM, xmin_source, 0, px, py, trUTMLL, trLLUTM, 1, False, dx[2] - 3.1 * scale * fSize / 1.5, dy[3], dy0[3], dy1[1], 'Bottom', 'Center', 'UTMLeftTest', fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, range(1), geo_bb_or) rulechild = ruletest.children()[0] if rulechild.settings().fieldName == 'fail': rangeLat = range(2, UTM_num_y + 1) else: rangeLat = range(1, UTM_num_y + 1) for u in rangeLat: if u == min(rangeLat): extra_dist = -2.0 * scale * fSize / 1.5 else: extra_dist = 0 root_rule = self.utm_grid_labeler( root_rule, xmin_UTM, ymin_UTM, xmin_source, 0, px, py, trUTMLL, trLLUTM, u, False, dx[2] + extra_dist, dy[3], dy0[3], dy1[1], 'Bottom', 'Center', 'UTMLeft' + str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeLat, geo_bb_or) # Right rangeLat = range(1, UTM_num_y + 1) for u in rangeLat: root_rule = self.utm_grid_labeler( root_rule, xmax_UTM, ymin_UTM, xmax_source, 0, px, py, trUTMLL, trLLUTM, u, False, dx[3], dy[3], dy0[3], dy1[1], '', 'Center', 'UTMRight' + str(1), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeLat, geo_bb_or) return root_rule
def __init__(self): QMainWindow.__init__(self) #self.setWindowFlags(Qt.CustomizeWindowHint) #self.setWindowFlags(Qt.WindowMinMaxButtonsHint) # creating map canvas, which draws the maplayers # setting up features like canvas color self.canvas = QgsMapCanvas() self.canvas.setMinimumSize(550, 700) self.canvas.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.canvas.setCanvasColor(Qt.white) self.canvas.setSelectionColor(QColor(255, 255, 26, 200)) self.canvas.enableAntiAliasing(True) self.canvas.setParallelRenderingEnabled(True) # empty list for selected polygons self.selected_features = [] # setting up label settings: object below houses all of them self.label_settings = QgsPalLayerSettings() # object for text settings text_format = QgsTextFormat() text_format.setFont(QFont("Helvetica", 12)) text_format.setSize(7) # setting up a white buffer around the labels buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(0.65) buffer_settings.setColor(Qt.white) text_format.setBuffer(buffer_settings) # label settings: # fieldName = which field is shown as the label (currently Finnish name) # placement = labels can be placed differently in relation to one another # - see documentation for details self.label_settings.setFormat(text_format) self.label_settings.fieldName = "namefin" self.label_settings.placement = 0 self.label_settings.enabled = True # Qmainwindow requires a central widget. Canvas is placed self.setCentralWidget(self.canvas) # creating each desired action self.actionGet = QAction("Return selected and close", self) self.actionPan = QAction("Pan tool", self) self.actionSelect = QAction("Select tool", self) self.actionClear = QAction("Clear selection", self) self.actionCancel = QAction("Cancel and close", self) # these two function as on/off. the rest are clickable self.actionPan.setCheckable(True) self.actionSelect.setCheckable(True) # when actions are clicked, do corresponding function self.actionPan.triggered.connect(self.pan) self.actionSelect.triggered.connect(self.select) self.actionClear.triggered.connect(self.clearSelection) self.actionGet.triggered.connect(self.finishedSelection) self.actionCancel.triggered.connect(self.cancel) # toolbar at the top of the screen: houses actions as buttons # change order here to change their placement on window self.toolbar = self.addToolBar("Canvas actions") self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu) self.toolbar.setMovable(False) self.toolbar.addAction(self.actionGet) self.toolbar.addAction(self.actionPan) self.toolbar.addAction(self.actionSelect) self.toolbar.addAction(self.actionClear) self.toolbar.addAction(self.actionCancel) # link actions to premade map tools self.toolPan = QgsMapToolPan(self.canvas) self.toolPan.setAction(self.actionPan) self.toolSelect = QgsMapToolIdentifyFeature(self.canvas) self.toolSelect.setAction(self.actionSelect) self.toolSelect.featureIdentified.connect(self.selectFeature) self.blocks_flag = False self.selection_rectangle = False # set select tool as default self.select()
def test_line_settings(self): """ Test line settings """ settings = QgsLabelLineSettings() settings.setPlacementFlags(QgsLabeling.LinePlacementFlag.OnLine) self.assertEqual(settings.placementFlags(), QgsLabeling.LinePlacementFlag.OnLine) settings.setPlacementFlags( QgsLabeling.LinePlacementFlag.OnLine | QgsLabeling.LinePlacementFlag.MapOrientation) self.assertEqual( settings.placementFlags(), QgsLabeling.LinePlacementFlag.OnLine | QgsLabeling.LinePlacementFlag.MapOrientation) settings.setMergeLines(True) self.assertTrue(settings.mergeLines()) settings.setMergeLines(False) self.assertFalse(settings.mergeLines()) settings.setAddDirectionSymbol(True) self.assertTrue(settings.addDirectionSymbol()) settings.setAddDirectionSymbol(False) self.assertFalse(settings.addDirectionSymbol()) settings.setLeftDirectionSymbol('left') self.assertEqual(settings.leftDirectionSymbol(), 'left') settings.setRightDirectionSymbol('right') self.assertEqual(settings.rightDirectionSymbol(), 'right') settings.setReverseDirectionSymbol(True) self.assertTrue(settings.reverseDirectionSymbol()) settings.setReverseDirectionSymbol(False) self.assertFalse(settings.reverseDirectionSymbol()) settings.setDirectionSymbolPlacement( QgsLabelLineSettings.DirectionSymbolPlacement.SymbolBelow) self.assertEqual( settings.directionSymbolPlacement(), QgsLabelLineSettings.DirectionSymbolPlacement.SymbolBelow) settings.setDirectionSymbolPlacement( QgsLabelLineSettings.DirectionSymbolPlacement.SymbolAbove) self.assertEqual( settings.directionSymbolPlacement(), QgsLabelLineSettings.DirectionSymbolPlacement.SymbolAbove) settings.setOverrunDistance(5.6) self.assertEqual(settings.overrunDistance(), 5.6) settings.setOverrunDistanceUnit(QgsUnitTypes.RenderInches) self.assertEqual(settings.overrunDistanceUnit(), QgsUnitTypes.RenderInches) scale = QgsMapUnitScale(1, 2) settings.setOverrunDistanceMapUnitScale(scale) self.assertEqual(settings.overrunDistanceMapUnitScale().minScale, 1) self.assertEqual(settings.overrunDistanceMapUnitScale().maxScale, 2) settings.setLineAnchorPercent(0.3) self.assertEqual(settings.lineAnchorPercent(), 0.3) # check that compatibility code works pal_settings = QgsPalLayerSettings() pal_settings.placementFlags = QgsPalLayerSettings.OnLine | QgsPalLayerSettings.MapOrientation self.assertEqual(pal_settings.placementFlags, 9) self.assertTrue( pal_settings.lineSettings().placementFlags(), QgsLabeling.LinePlacementFlag.OnLine | QgsLabeling.LinePlacementFlag.MapOrientation) pal_settings.mergeLines = True self.assertTrue(pal_settings.mergeLines) self.assertTrue(pal_settings.lineSettings().mergeLines()) pal_settings.mergeLines = False self.assertFalse(pal_settings.mergeLines) self.assertFalse(pal_settings.lineSettings().mergeLines()) pal_settings.addDirectionSymbol = True self.assertTrue(pal_settings.addDirectionSymbol) self.assertTrue(pal_settings.lineSettings().addDirectionSymbol()) pal_settings.addDirectionSymbol = False self.assertFalse(pal_settings.addDirectionSymbol) self.assertFalse(pal_settings.lineSettings().addDirectionSymbol()) pal_settings.leftDirectionSymbol = 'l' self.assertEqual(pal_settings.leftDirectionSymbol, 'l') self.assertEqual(pal_settings.lineSettings().leftDirectionSymbol(), 'l') pal_settings.rightDirectionSymbol = 'r' self.assertEqual(pal_settings.rightDirectionSymbol, 'r') self.assertEqual(pal_settings.lineSettings().rightDirectionSymbol(), 'r') pal_settings.reverseDirectionSymbol = True self.assertTrue(pal_settings.reverseDirectionSymbol) self.assertTrue(pal_settings.lineSettings().reverseDirectionSymbol()) pal_settings.reverseDirectionSymbol = False self.assertFalse(pal_settings.reverseDirectionSymbol) self.assertFalse(pal_settings.lineSettings().reverseDirectionSymbol()) pal_settings.placeDirectionSymbol = QgsPalLayerSettings.SymbolAbove self.assertEqual(pal_settings.placeDirectionSymbol, 1) self.assertTrue( pal_settings.lineSettings().directionSymbolPlacement(), QgsLabelLineSettings.DirectionSymbolPlacement.SymbolAbove) pal_settings.overrunDistance = 4.2 self.assertEqual(pal_settings.overrunDistance, 4.2) self.assertTrue(pal_settings.lineSettings().overrunDistance(), 4.2) pal_settings.overrunDistanceUnit = QgsUnitTypes.RenderInches self.assertEqual(pal_settings.overrunDistanceUnit, QgsUnitTypes.RenderInches) self.assertTrue(pal_settings.lineSettings().overrunDistanceUnit(), QgsUnitTypes.RenderInches) pal_settings.overrunDistanceMapUnitScale = scale self.assertEqual(pal_settings.overrunDistanceMapUnitScale.minScale, 1) self.assertEqual(pal_settings.overrunDistanceMapUnitScale.maxScale, 2) self.assertTrue( pal_settings.lineSettings().overrunDistanceMapUnitScale().minScale, 1) self.assertTrue( pal_settings.lineSettings().overrunDistanceMapUnitScale().maxScale, 2)
def showMarkDaSoc(self): try: self.putDistances() flag = FlightPlanBaseDlg.btnConstruct_Click(self) # if not flag: # return point3dThr = self.parametersPanel.pnlThrPosition.Point3d point3dFaf = self.parametersPanel.pnlFafPosition.Point3d point3dMapt = self.parametersPanel.pnlMaPtPosition.Point3d if self.socPoint3d == None: return socLayer = AcadHelper.createVectorLayer("SOC_MAPt_" + self.surfaceType, QGis.Point) AcadHelper.setGeometryAndAttributesInLayer(socLayer, self.socPoint3d, False, {"Caption":"SOC"}) AcadHelper.setGeometryAndAttributesInLayer(socLayer, point3dMapt, False, {"Caption":"MAPt"}) QgisHelper.appendToCanvas(define._canvas, [socLayer], self.surfaceType) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(socLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.AroundPoint palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(socLayer) # QgisHelper.zoomToLayers([socLayer]) self.resultLayerList = [socLayer] return socLayer except: pass
def postProcessLayer(self, layer, context, feedback): _ = feedback, context layer.setLabelsEnabled(True) pal = QgsPalLayerSettings() # Expression combinant les nom d'habitat et du faciès pal.fieldName = "|| ' - ' || ".join(self.fields) pal.isExpression = True # Mais ce label est trop long # utilisation du faciès pour le label # et du nom pour le rendu pal.fieldName = self.fields[1] pal.isExpression = False pal.labelPerPart = True pal.placement = QgsPalLayerSettings.OverPoint txt_buff = QgsTextBufferSettings() txt_buff.setEnabled(True) txt_format = pal.format() txt_format.setBuffer(txt_buff) pal.setFormat(txt_format) layer.setLabeling(QgsVectorLayerSimpleLabeling(pal)) renderer = layer.renderer() symbol = renderer.symbol() symbol.setSize(6) # Symbologie à partir du champs nom de l'habitat index = layer.fields().indexOf(self.fields[0]) values = layer.uniqueValues(index) color = QgsRandomColorRamp() color.setTotalColorCount(len(values)) categories = [] for i, value in enumerate(values): symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) symbol.setColor(color.color(i)) symbol.setSize(5) category = QgsRendererCategory(value, symbol, value) categories.append(category) renderer = QgsCategorizedSymbolRenderer(self.fields[0], categories) layer.setRenderer(renderer) layer.triggerRepaint()
def btnConstruct_Click(self): flag = FlightPlanBaseSimpleDlg.btnConstruct_Click(self) if not flag: return constructionLayer = AcadHelper.createVectorLayer(SurfaceTypes.DmeTolerance, QGis.Line) point3d1 = self.parametersPanel.pnlDME.Point3d circleAreaList = [] # length = self.groundDistance.Metres / 5 # # rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) # point1 = Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() + length / 2) # point2 = Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2) captionCircleLine = [] centerPoint = None radius = 0.0 arc = None; resultPoint3dArrayList = [] if (self.groundDistance.Metres > 0): metres = self.dmeTolerance.valueMetres / 1.7; if (self.parametersPanel.cmbConstructionType.currentIndex() != 0): num1 = Unit.ConvertDegToRad(float(self.parametersPanel.pnlRadial.Value)); num2 = math.asin(min([1 / self.groundDistance.NauticalMiles, 1])); num3 = num1 + num2 num4 = num1 - num2 # arc = PolylineArea() # arc.Add(PolylineAreaPoint(point3d1, self.groundDistance.Metres)) arc = MathHelper.constructArc(point3d1, self.groundDistance.Metres, num3, num4, 30); point3d = MathHelper.distanceBearingPoint(point3d1, num1, self.groundDistance.Metres); captionCircleLine = [MathHelper.distanceBearingPoint(point3d, MathHelper.getBearing(point3d, point3d1) + math.pi / 2, self.groundDistance.Metres / 20), MathHelper.distanceBearingPoint(point3d, MathHelper.getBearing(point3d, point3d1) - math.pi / 2, self.groundDistance.Metres / 20)] num = -num1; if (self.parametersPanel.chbDrawRadial.isChecked()): line = PolylineArea([point3d1, point3d]); resultPoint3dArrayList.append([point3d1, point3d]) # AcadHelper.smethod_18(transaction, blockTableRecord, line, constructionLayer); else: arc = MathHelper.constructCircle(point3d1, self.groundDistance.Metres, 50); circleAreaList.append(PolylineArea(None, point3d1, self.groundDistance.Metres)) centerPoint = point3d1 radius = self.groundDistance.Metres point3d = MathHelper.distanceBearingPoint(point3d1, 0, self.groundDistance.Metres); length = self.groundDistance.Metres / 5 # rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) point1 = MathHelper.distanceBearingPoint(point3d, Unit.ConvertDegToRad(270), length / 4)#Point3D(point3d.get_X() - length / 4, point3d.get_Y()) point2 = MathHelper.distanceBearingPoint(point3d, Unit.ConvertDegToRad(90), length / 4)#Point3D(point3d.get_X() + length / 4, point3d.get_Y()) captionCircleLine = [point1, point2] num = 0; resultPoint3dArrayList.append(arc) # AcadHelper.smethod_18(transaction, blockTableRecord, arc, constructionLayer); if (self.parametersPanel.chbWriteText.isChecked()): nauticalMiles = self.groundDistance.NauticalMiles; # DBText dBText = AcadHelper.smethod_138(string.Format("{0} DME", nauticalMiles.ToString("0.#")), point3d, metres, 1); # dBText.set_Rotation(num); # AcadHelper.smethod_18(transaction, blockTableRecord, dBText, constructionLayer); if (self.parametersPanel.chbDrawDmeTol.isVisible() and self.parametersPanel.chbDrawDmeTol.isChecked() and self.dmeTolerance.IsValid() and arc != None): offsetCurf = QgisHelper.offsetCurve(arc, self.dmeTolerance.Metres) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius + self.dmeTolerance.Metres)) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = offsetCurf[0] offsetCurf.append(endPoint) resultPoint3dArrayList.append(offsetCurf) # foreach (Entity offsetCurf in arc.GetOffsetCurves(self.dmeTolerance.Metres)) # { # AcadHelper.smethod_19(transaction, blockTableRecord, offsetCurf, constructionLayer, 5); # } entity = QgisHelper.offsetCurve(arc, -(self.dmeTolerance.Metres + self.slantTolerance.Metres)) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius -(self.dmeTolerance.Metres + self.slantTolerance.Metres))) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = entity[0] entity.append(endPoint) resultPoint3dArrayList.append(entity) # foreach (Entity entity in arc.GetOffsetCurves(-(self.dmeTolerance.Metres + self.slantTolerance.Metres))) # { # AcadHelper.smethod_19(transaction, blockTableRecord, entity, constructionLayer, 5); # } # } if (self.parametersPanel.chbDrawSlantTol.isVisible() and self.parametersPanel.chbDrawSlantTol.isChecked() and self.slantTolerance.IsValid() and arc != None): offsetCurf1 = QgisHelper.offsetCurve(arc, -self.slantTolerance.Metres) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius -self.slantTolerance.Metres)) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = offsetCurf1[0] offsetCurf1.append(endPoint) resultPoint3dArrayList.append(offsetCurf1) # foreach (Entity offsetCurf1 in arc.GetOffsetCurves(-self.slantTolerance.Metres)) # { # AcadHelper.smethod_19(transaction, blockTableRecord, offsetCurf1, constructionLayer, 2); # } # } if (self.parametersPanel.chbInsertSymbol.isChecked()): length = self.groundDistance.Metres / 5 rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) point1 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(315), length / 2)#Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() + length / 2) point2 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(225), length / 2)#Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2) point3 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(135), length / 2)#Point3D(point3d1.get_X() + length / 2, point3d1.get_Y() - length / 2) point4 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(45), length / 2)#Point3D(point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2) resultPoint3dArrayList.append([point1, point2, point3, point4, point1]) # Symbol symbol = new Symbol(SymbolType.Dme); # AcadHelper.smethod_57(transaction, blockTableRecord, symbol.BlockName, symbol.BlockFileName, point3d1, new Scale3d(1), 0, constructionLayer, None); # } for point3dArray in resultPoint3dArrayList: if (self.parametersPanel.cmbConstructionType.currentIndex() != 0): bulge = MathHelper.smethod_60(point3dArray[0], point3dArray[int(len(point3dArray)/2)], point3dArray[len(point3dArray)-1]) AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, point3dArray, False, {"Bulge":bulge}) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: for area in circleAreaList: AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, area) if self.parametersPanel.chbInsertSymbol.isChecked(): AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, [point1, point2, point3, point4, point1]) if (self.parametersPanel.chbWriteText.isChecked()): AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, captionCircleLine, False, {"Caption":"3DME"} ) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '12', "") palSetting.writeToLayer(constructionLayer) QgisHelper.appendToCanvas(define._canvas, [constructionLayer], self.surfaceType, True) QgisHelper.zoomToLayers([constructionLayer]) self.resultLayerList = [constructionLayer]
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 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 prepare_ordered_marker(self, coords, idx): """ Try to display nice marker on a point layer, showing the order of the path computed by OSRM. """ self.tsp_marker_lr = QgsVectorLayer( "Point?crs=epsg:4326&field=id:integer" "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)", "tsp_markers_osrm{}".format(self.nb_route), "memory") symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType()) symbol.setSize(4.5) symbol.setColor(QtGui.QColor("yellow")) ordered_pts = \ [coords[i["waypoint_index"]] for i in self.parsed['waypoints']] print("ordered_pts : ", ordered_pts) features = [] for nb, pt in enumerate(ordered_pts): ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt))) ft.setAttributes([nb, nb + 1, coords.index(pt)]) features.append(ft) self.tsp_marker_lr.dataProvider().addFeatures(features) pal_lyr = QgsPalLayerSettings() pal_lyr.readFromLayer(self.tsp_marker_lr) pal_lyr.enabled = True pal_lyr.fieldName = 'TSP_nb' pal_lyr.placement = QgsPalLayerSettings.OverPoint pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '12', '') pal_lyr.writeToLayer(self.tsp_marker_lr) self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol)) QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
def getPopups(layer, safeLayerName, highlight, popupsOnHover, popup): palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) fields = layer.pendingFields() field_names = popup.keys() field_vals = popup.values() html_prov = False f = palyr.fieldName table = "" for field in popup: tablestart = "'<table>\\" row = "" for field, val in zip(field_names, field_vals): fieldIndex = fields.indexFromName(unicode(field)) formCfg = layer.editFormConfig() editorWidget = formCfg.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): continue row += """ <tr>\\""" if val == 'inline label': row += """ <th scope="row">""" row += layer.attributeDisplayName(fieldIndex) row += """</th>\\ <td>""" else: row += """ <td colspan="2">""" if val == "header label": row += '<strong>' row += layer.attributeDisplayName(fieldIndex) row += '</strong><br />' row += "' + " row += "(feature.properties[\'" + unicode(field) + "\'] " row += "!== null ? " if (editorWidget == QgsVectorLayer.Photo or editorWidget == 'Photo'): row += "'<img src=\"images/' + " row += "String(feature.properties['" + unicode(field) row += "']).replace(/[\\\/:]/g, '_').trim()" row += " + '\">' : '') + '" else: row += "Autolinker.link(" row += "String(feature.properties['" + unicode(field) row += "'])) : '') + '" row += """</td>\\ </tr>\\""" tableend = """ </table>'""" table = tablestart + row + tableend if popup != 0 and table != "": popFuncs = popFuncsScript(table) else: popFuncs = "" new_pop = popupScript(safeLayerName, popFuncs, highlight, popupsOnHover) return new_pop, popFuncs
class TestPointBase(object): def __init__(self): """Dummy assignments, intended to be overridden in subclasses""" self.lyr = QgsPalLayerSettings() """:type: QgsPalLayerSettings""" # noinspection PyArgumentList self._TestFont = QFont() # will become a standard test font self._Canvas = None """:type: QgsMapCanvas""" # custom mismatches per group/test (should not mask any needed anomaly) # e.g. self._Mismatches['TestClassName'] = 300 # check base output class's checkTest() or sublcasses for any defaults self._Mismatches = dict() # custom color tolerances per group/test: 1 - 20 (0 default, 20 max) # (should not mask any needed anomaly) # e.g. self._ColorTols['TestClassName'] = 10 # check base output class's checkTest() or sublcasses for any defaults self._ColorTols = dict() # noinspection PyMethodMayBeStatic def checkTest(self, **kwargs): """Intended to be overridden in subclasses""" pass def test_default_label(self): # Default label placement, with text size in points self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_text_size_map_unit(self): # Label text size in map units format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_text_color(self): self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 # Label color change format = self.lyr.format() format.setColor(Qt.blue) self.lyr.setFormat(format) self.checkTest() def test_background_rect(self): self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 format = self.lyr.format() format.background().setEnabled(True) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 1 self.checkTest() def test_background_rect_w_offset(self): # Label rectangular background self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 # verify fix for issues # https://issues.qgis.org/issues/9057 # http://gis.stackexchange.com/questions/86900 format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setOffsetUnit(QgsUnitTypes.RenderMapUnits) format.background().setOffset(QPointF(-2900.0, -450.0)) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_background_svg(self): # Label SVG background format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setType(QgsTextBackgroundSettings.ShapeSVG) svg = os.path.join( svgSymbolsPath(), 'backgrounds', 'background_square.svg') format.background().setSvgFile(svg) format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) format.background().setSize(QSizeF(100.0, 0.0)) self.lyr.setFormat(format) self._Mismatches['TestComposerPdfVsComposerPoint'] = 580 self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_background_svg_w_offset(self): # Label SVG background format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setType(QgsTextBackgroundSettings.ShapeSVG) svg = os.path.join( svgSymbolsPath(), 'backgrounds', 'background_square.svg') format.background().setSvgFile(svg) format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) format.background().setSize(QSizeF(100.0, 0.0)) format.background().setOffsetUnit(QgsUnitTypes.RenderMapUnits) format.background().setOffset(QPointF(-2850.0, 500.0)) self.lyr.setFormat(format) self._Mismatches['TestComposerPdfVsComposerPoint'] = 760 self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_partials_labels_enabled(self): # Set Big font size format = self.lyr.format() font = QFont(self._TestFont) format.setFont(font) format.setSize(84) self.lyr.setFormat(format) # Enable partials labels engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, True) self._TestMapSettings.setLabelingEngineSettings(engine_settings) self._Mismatches['TestCanvasPoint'] = 779 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_partials_labels_disabled(self): # Set Big font size format = self.lyr.format() font = QFont(self._TestFont) format.setFont(font) format.setSize(84) self.lyr.setFormat(format) # Disable partials labels engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) self._TestMapSettings.setLabelingEngineSettings(engine_settings) self.checkTest() def test_buffer(self): # Label with buffer format = self.lyr.format() format.buffer().setEnabled(True) format.buffer().setSize(2) self.lyr.setFormat(format) self.checkTest() def test_shadow(self): # Label with shadow format = self.lyr.format() format.shadow().setEnabled(True) format.shadow().setOffsetDistance(2) format.shadow().setOpacity(1) self.lyr.setFormat(format) self.checkTest() def test_letter_spacing(self): # Modified letter spacing format = self.lyr.format() font = QFont(self._TestFont) font.setLetterSpacing(QFont.AbsoluteSpacing, 3.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest() def test_word_spacing(self): # Modified word spacing format = self.lyr.format() font = QFont(self._TestFont) font.setWordSpacing(20.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest()
def exportStyles(layers, folder, clustered): stylesFolder = os.path.join(folder, "styles") QDir().mkpath(stylesFolder) legendFolder = os.path.join(stylesFolder, "legend") QDir().mkpath(legendFolder) for count, (layer, cluster) in enumerate(zip(layers, clustered)): sln = safeName(layer.name()) + unicode(count) if layer.type() != layer.VectorLayer: continue labelsEnabled = unicode( layer.customProperty("labeling/enabled")).lower() == "true" if (labelsEnabled): labelField = layer.customProperty("labeling/fieldName") if labelField != "": if unicode(layer.customProperty( "labeling/isExpression")).lower() == "true": exprFilename = os.path.join(folder, "resources", "qgis2web_expressions.js") fieldName = layer.customProperty("labeling/fieldName") name = compile_to_file(fieldName, "label_%s" % sln, "OpenLayers3", exprFilename) js = "%s(context)" % (name) js = js.strip() labelText = js else: fieldIndex = layer.pendingFields().indexFromName( labelField) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): labelField = "q2wHide_" + labelField labelText = ('feature.get("%s")' % labelField.replace('"', '\\"')) else: labelText = '""' else: labelText = '""' defs = "var size = 0;\n" try: renderer = layer.rendererV2() layer_alpha = layer.layerTransparency() if isinstance(renderer, QgsSingleSymbolRendererV2): symbol = renderer.symbol() style = "var style = " + getSymbolAsStyle( symbol, stylesFolder, layer_alpha, renderer) legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( symbol, QSize(16, 16)) legendIcon.save(os.path.join(legendFolder, sln + ".png")) value = 'var value = ""' elif isinstance(renderer, QgsCategorizedSymbolRendererV2): cluster = False defs += """function categories_%s(feature, value, size) { switch(value.toString()) {""" % sln cats = [] for cnt, cat in enumerate(renderer.categories()): legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( cat.symbol(), QSize(16, 16)) legendIcon.save( os.path.join(legendFolder, sln + "_" + unicode(cnt) + ".png")) if (cat.value() is not None and cat.value() != "" and not isinstance(cat.value(), QPyNullVariant)): categoryStr = "case '%s':" % unicode( cat.value()).replace("'", "\\'") else: categoryStr = "default:" categoryStr += ''' return %s; break;''' % (getSymbolAsStyle(cat.symbol(), stylesFolder, layer_alpha, renderer)) cats.append(categoryStr) defs += "\n".join(cats) + "}};" classAttr = renderer.classAttribute() fieldIndex = layer.pendingFields().indexFromName(classAttr) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): classAttr = "q2wHide_" + classAttr value = ('var value = feature.get("%s");' % classAttr) style = ('var style = categories_%s(feature, value, size)' % sln) elif isinstance(renderer, QgsGraduatedSymbolRendererV2): cluster = False varName = "ranges_" + sln defs += "var %s = [" % varName ranges = [] for cnt, ran in enumerate(renderer.ranges()): legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( ran.symbol(), QSize(16, 16)) legendIcon.save( os.path.join(legendFolder, sln + "_" + unicode(cnt) + ".png")) symbolstyle = getSymbolAsStyle(ran.symbol(), stylesFolder, layer_alpha, renderer) ranges.append( '[%f, %f, %s]' % (ran.lowerValue(), ran.upperValue(), symbolstyle)) defs += ",\n".join(ranges) + "];" classAttr = renderer.classAttribute() fieldIndex = layer.pendingFields().indexFromName(classAttr) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): classAttr = "q2wHide_" + classAttr value = ('var value = feature.get("%s");' % classAttr) style = '''var style = %(v)s[0][2]; for (i = 0; i < %(v)s.length; i++){ var range = %(v)s[i]; if (value > range[0] && value<=range[1]){ style = range[2]; } }''' % { "v": varName } elif isinstance(renderer, QgsRuleBasedRendererV2): cluster = False template = """ function rules_%s(feature, value) { var context = { feature: feature, variables: {} }; // Start of if blocks and style check logic %s else { return %s; } } var style = rules_%s(feature, value); """ elsejs = "[]" js = "" root_rule = renderer.rootRule() rules = root_rule.children() expFile = os.path.join(folder, "resources", "qgis2web_expressions.js") ifelse = "if" for count, rule in enumerate(rules): symbol = rule.symbol() styleCode = getSymbolAsStyle(symbol, stylesFolder, layer_alpha, renderer) name = "".join((sln, "rule", unicode(count))) exp = rule.filterExpression() if rule.isElse(): elsejs = styleCode continue name = compile_to_file(exp, name, "OpenLayers3", expFile) js += """ %s (%s(context)) { return %s; } """ % (ifelse, name, styleCode) js = js.strip() ifelse = "else if" value = ("var value = '';") style = template % (sln, js, elsejs, sln) else: style = "" if layer.customProperty("labeling/fontSize"): size = float(layer.customProperty("labeling/fontSize")) * 1.3 else: size = 10 italic = layer.customProperty("labeling/fontItalic") bold = layer.customProperty("labeling/fontWeight") r = layer.customProperty("labeling/textColorR") g = layer.customProperty("labeling/textColorG") b = layer.customProperty("labeling/textColorB") if (r or g or b) is None: color = "rgba(0, 0, 0, 1)" else: color = "rgba(%s, %s, %s, 1)" % (r, g, b) face = layer.customProperty("labeling/fontFamily") if face is None: face = "," else: face = " \\'%s\\'," % face palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) sv = palyr.scaleVisibility if sv: min = float(palyr.scaleMin) max = float(palyr.scaleMax) if min != 0: min = 1 / ((1 / min) * 39.37 * 90.7) max = 1 / ((1 / max) * 39.37 * 90.7) labelRes = " && resolution > %(min)d " % {"min": min} labelRes += "&& resolution < %(max)d" % {"max": max} else: labelRes = "" buffer = palyr.bufferDraw if buffer: bufferColor = palyr.bufferColor.name() bufferWidth = palyr.bufferSize stroke = """ stroke: new ol.style.Stroke({ color: "%s", width: %d }),""" % (bufferColor, bufferWidth) else: stroke = "" if style != "": style = getStyle(style, cluster, labelRes, labelText, sln, size, face, color, value) else: style = "''" except Exception, e: style = """{ /* """ + traceback.format_exc() + " */}" QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web", level=QgsMessageLog.CRITICAL) path = os.path.join(stylesFolder, sln + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write('''%(defs)s var styleCache_%(name)s={} var style_%(name)s = %(style)s;''' % { "defs": defs, "name": sln, "style": style })
def convert_fdo_annotations(dest_layer: QgsVectorLayer, context): # pylint: disable=unused-argument """ Converts FDO annotations """ # one label class, use simple labeling label_settings = QgsPalLayerSettings() label_settings.fieldName = 'TextString' label_settings.drawLabels = True label_settings.placement = QgsPalLayerSettings.OverPoint label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.Family, QgsProperty.fromField('FontName')) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.Size, QgsProperty.fromField('FontSize')) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.Bold, QgsProperty.fromField('Bold')) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.Italic, QgsProperty.fromField('Italic')) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.Underline, QgsProperty.fromField('Underline')) quadrant_property = QgsProperty.fromExpression("""case when "VerticalAlignment" = 0 then -- top case when "HorizontalAlignment" = 0 then 0 when "HorizontalAlignment" = 1 then 1 when "HorizontalAlignment" = 2 then 2 end when "VerticalAlignment" = 1 then -- center case when "HorizontalAlignment" = 0 then 3 when "HorizontalAlignment" = 1 then 4 when "HorizontalAlignment" = 2 then 5 end when "VerticalAlignment" in (2,3) then -- baseline, bottom case when "HorizontalAlignment" = 0 then 6 when "HorizontalAlignment" = 1 then 7 when "HorizontalAlignment" = 2 then 8 end end""") label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.OffsetQuad, quadrant_property) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.LabelRotation, QgsProperty.fromExpression('360-"Angle"')) label_settings.dataDefinedProperties().setProperty( QgsPalLayerSettings.OffsetXY, QgsProperty.fromExpression( ' concat( "XOffset" ,\',\', "YOffset" )')) labeling = QgsVectorLayerSimpleLabeling(label_settings) dest_layer.setLabeling(labeling)
def __init__(self): """Dummy assignments, intended to be overriden in subclasses""" self.lyr = QgsPalLayerSettings() self._TestFont = QFont()
for column in columns: if column.name == columnName: column.hidden = not visible break config.setColumns( columns ) layer.setAttributeTableConfig( config ) lager = iface.activeLayer() if not lager.isEditable(): iface.actionToggleEditing().trigger() lager.dataProvider().addAttributes([QgsField("Text_X", QVariant.Double, 'double', 10, 5), QgsField("Text_Y", QVariant.Double, 'double', 10, 5), QgsField("Text_Ri", QVariant.Double, 'double', 3, 2), QgsField("Text_Vis", QVariant.Int, "", 3)]) lager.updateFields() lager.commitChanges() lager.setDefaultValueExpression(lager.fieldNameIndex("Text_Vis"), '1') palager = QgsPalLayerSettings() palager.readFromLayer(lager) palager.enabled = True palager.setDataDefinedProperty(QgsPalLayerSettings.PositionX, True, False, '', "Text_X") palager.setDataDefinedProperty(QgsPalLayerSettings.PositionY, True, False, '', "Text_Y") palager.setDataDefinedProperty(QgsPalLayerSettings.Rotation, True, False, '', "Text_Ri") palager.setDataDefinedProperty(QgsPalLayerSettings.Show, True, False, '', "Text_Vis") setColumnVisibility( lager, 'Text_X', False) setColumnVisibility( lager, 'Text_Y', False) setColumnVisibility( lager, 'Text_Ri', False) setColumnVisibility( lager, 'Text_Vis', False) palager.writeToLayer(lager) rader = lager.getFeatures() for rad in rader: rad['Text_Vis'] = 1 lager.updateFeature(rad)
def grid_labeler(self, coord_base_x, coord_base_y, px, py, u, t, dx, dy, desc, fSize, fontType, expression_str, trLLUTM, llcolor, layer_bound, trUTMLL): pgrid = QgsPoint(coord_base_x + px * u, coord_base_y + py * t) pgrid.transform(trLLUTM) pgrid = QgsPoint(pgrid.x() + dx, pgrid.y() + dy) if layer_bound.crs().isGeographic() == True: pgrid.transform(trUTMLL) #Label Format Settings settings = QgsPalLayerSettings() settings.placement = 1 settings.isExpression = True textprop = QgsTextFormat() textprop.setColor(llcolor) textprop.setSizeUnit(4) textprop.setSize(fSize * 2.8346) textprop.setFont(QFont(fontType)) textprop.setLineHeight(1) settings.setFormat(textprop) settings.fieldName = expression_str #Label Position settings.geometryGeneratorEnabled = True settings.geometryGenerator = ("make_point({}, {})".format( pgrid.x(), pgrid.y())) datadefined = QgsPropertyCollection() datadefined.property(20).setExpressionString('True') datadefined.property(20).setActive(True) datadefined.property(15).setExpressionString('True') datadefined.property(15).setActive(True) datadefined.property(77).setExpressionString('2') datadefined.property(77).setActive(True) #Creating and Activating Labeling Rule settings.setDataDefinedProperties(datadefined) rule = QgsRuleBasedLabeling.Rule(settings) rule.setDescription(desc) rule.setActive(True) return rule
def testAuxiliaryFieldWidgets(self): # Init storage s = QgsAuxiliaryStorage() self.assertTrue(s.isValid()) # Create a new auxiliary layer with 'pk' as key vl = createLayer() pkf = vl.fields().field(vl.fields().indexOf('pk')) al = s.createAuxiliaryLayer(pkf, vl) self.assertTrue(al.isValid()) # Set the auxiliary layer to the vector layer vl.setAuxiliaryLayer(al) # Add a visible property p = QgsPropertyDefinition('propName', QgsPropertyDefinition.DataTypeNumeric, '', '', 'user') self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertFalse(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), '') tested = False for c in vl.attributeTableConfig().columns(): if c.name == afName: self.assertFalse(c.hidden) tested = True break self.assertTrue(tested) # Add a hidden property p = QgsPalLayerSettings.propertyDefinitions()[ QgsPalLayerSettings.PositionX] self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertTrue(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), 'Hidden') tested = False for c in vl.attributeTableConfig().columns(): if c.name == afName: self.assertTrue(c.hidden) tested = True break self.assertTrue(tested) # Add a color property p = QgsSymbolLayer.propertyDefinitions()[ QgsSymbolLayer.PropertyFillColor] self.assertTrue(al.addAuxiliaryField(p)) index = al.indexOfPropertyDefinition(p) self.assertFalse(al.isHiddenProperty(index)) afName = QgsAuxiliaryLayer.nameFromProperty(p, True) index = vl.fields().indexOf(afName) setup = vl.editorWidgetSetup(index) self.assertEqual(setup.type(), 'Color')
class MapWindow(QMainWindow): """This class offers a canvas and tools to select polygons from a vector layer provided by the main app.""" # signal emitted when polygons succesfully selected finished = pyqtSignal() def __init__(self): QMainWindow.__init__(self) #self.setWindowFlags(Qt.CustomizeWindowHint) #self.setWindowFlags(Qt.WindowMinMaxButtonsHint) # creating map canvas, which draws the maplayers # setting up features like canvas color self.canvas = QgsMapCanvas() self.canvas.setMinimumSize(550, 700) self.canvas.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.canvas.setCanvasColor(Qt.white) self.canvas.setSelectionColor(QColor(255, 255, 26, 200)) self.canvas.enableAntiAliasing(True) self.canvas.setParallelRenderingEnabled(True) # empty list for selected polygons self.selected_features = [] # setting up label settings: object below houses all of them self.label_settings = QgsPalLayerSettings() # object for text settings text_format = QgsTextFormat() text_format.setFont(QFont("Helvetica", 12)) text_format.setSize(7) # setting up a white buffer around the labels buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(0.65) buffer_settings.setColor(Qt.white) text_format.setBuffer(buffer_settings) # label settings: # fieldName = which field is shown as the label (currently Finnish name) # placement = labels can be placed differently in relation to one another # - see documentation for details self.label_settings.setFormat(text_format) self.label_settings.fieldName = "namefin" self.label_settings.placement = 0 self.label_settings.enabled = True # Qmainwindow requires a central widget. Canvas is placed self.setCentralWidget(self.canvas) # creating each desired action self.actionGet = QAction("Return selected and close", self) self.actionPan = QAction("Pan tool", self) self.actionSelect = QAction("Select tool", self) self.actionClear = QAction("Clear selection", self) self.actionCancel = QAction("Cancel and close", self) # these two function as on/off. the rest are clickable self.actionPan.setCheckable(True) self.actionSelect.setCheckable(True) # when actions are clicked, do corresponding function self.actionPan.triggered.connect(self.pan) self.actionSelect.triggered.connect(self.select) self.actionClear.triggered.connect(self.clearSelection) self.actionGet.triggered.connect(self.finishedSelection) self.actionCancel.triggered.connect(self.cancel) # toolbar at the top of the screen: houses actions as buttons # change order here to change their placement on window self.toolbar = self.addToolBar("Canvas actions") self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu) self.toolbar.setMovable(False) self.toolbar.addAction(self.actionGet) self.toolbar.addAction(self.actionPan) self.toolbar.addAction(self.actionSelect) self.toolbar.addAction(self.actionClear) self.toolbar.addAction(self.actionCancel) # link actions to premade map tools self.toolPan = QgsMapToolPan(self.canvas) self.toolPan.setAction(self.actionPan) self.toolSelect = QgsMapToolIdentifyFeature(self.canvas) self.toolSelect.setAction(self.actionSelect) self.toolSelect.featureIdentified.connect(self.selectFeature) self.blocks_flag = False self.selection_rectangle = False # set select tool as default self.select() def pan(self): """Simply activates the tool""" self.canvas.setMapTool(self.toolPan) def select(self): self.canvas.setMapTool(self.toolSelect) def addLayer(self, layer): """Called when user click button on the main plugin: receives a vector layer, sets up labels & rendering parameters and shows the layer.""" # empty output list in case function is called multiple times self.selected_features.clear() self.selection_rectangle = False # layer into a self variable self.layer = layer # add layer to project: required to show it on screen # False = do not show the layer on the legend listing nor draw on main canvas QgsProject.instance().addMapLayer(self.layer, False) # set up visual stuff self.layer.setLabelsEnabled(True) layer_labeling = QgsVectorLayerSimpleLabeling(self.label_settings) self.layer.setLabeling(layer_labeling) self.layer.renderer().symbol().setColor(QColor(220, 220, 220)) # select tool needs a vector layer assigned to it self.toolSelect.setLayer(self.layer) self.canvas.setExtent(self.layer.extent()) # set layer to canvas self.canvas.setLayers([self.layer]) # show to user self.show() def addBlocksLayer(self, layer): self.selected_features.clear() self.blocks_flag = True self.layer = layer QgsProject.instance().addMapLayer(self.layer, False) self.layer.renderer().symbol().setColor(Qt.cyan) self.layer.renderer().symbol().setOpacity(0.30) # select tool needs a vector layer assigned to it self.toolSelect.setLayer(self.layer) self.canvas.setExtent(self.layer.extent()) # set layer to canvas """ url = ("http://86.50.168.160/geoserver/ows?service=wfs&version=2.0.0"+ "&request=GetFeature&typename=ogiir:maakuntajako_2018_4500k&pagingEnabled=true") self.bg_layer = QgsVectorLayer(url, "BACKGROUND-REMOVE", "WFS") """ self.bg_layer = QgsRasterLayer( "url=http://86.50.168.160/ogiir_cache/wmts/1.0.0/" + "WMTSCapabilities.xml&crs=EPSG:3067&dpiMode=7&format=image/" + "png&layers=taustakartta&styles=default&tileMatrixSet=GRIDI-FIN", 'GEOCUBES BG-LAYER - TEMPORARY', 'wms') if self.bg_layer.isValid(): QgsProject.instance().addMapLayer(self.bg_layer, False) self.canvas.setLayers([self.layer, self.bg_layer]) else: self.canvas.setLayers([self.layer]) self.show() def selectFeature(self, feat): """Activated when user clicks something on screen. This returns the clicked feature. The function does 2 things: 1. selects the feature on the map / deselects if already selected 2. adds features to a list in the same format (name, id_code) as they're stored in the 'Admin areas box' in the main file """ idx = feat.id() if self.blocks_flag: xmin = feat[0] ymax = feat[1] label = str(xmin) + "|" + str(ymax) else: code = feat[1] name = feat[2] label = name + "|" + code if label in self.selected_features: self.layer.deselect(idx) self.selected_features.remove(label) else: self.layer.select(idx) self.selected_features.append(label) def clearSelection(self): """Clear map selection and list on button click""" self.layer.removeSelection() self.selected_features.clear() def finishedSelection(self): """Activated when user clicks 'return selection'. Closes window and emits signal to indicate the job is finished""" self.close() self.finished.emit() def cancel(self): """In case user changes their mind. Does the same as above, but doesn't emit signal.""" self.close() def getSelection(self): """Returns list of selected features (polygons)""" return self.selected_features def getSelectionBbox(self): return self.selection_rectangle def closeEvent(self, event): """Activated anytime Mapwindow is closed either by buttons given or if the user finds some other way to close the window. Removes selection and deletes scrap maplayer.""" self.selection_rectangle = self.layer.boundingBoxOfSelected() self.layer.removeSelection() QgsProject.instance().removeMapLayer(self.layer) try: QgsProject.instance().removeMapLayer(self.bg_layer) except Exception: pass self.blocks_flag = False QMainWindow.closeEvent(self, event)
class TestPointBase(object): def __init__(self): """Dummy assignments, intended to be overridden in subclasses""" self.lyr = QgsPalLayerSettings() """:type: QgsPalLayerSettings""" # noinspection PyArgumentList self._TestFont = QFont() # will become a standard test font self._Canvas = None """:type: QgsMapCanvas""" # custom mismatches per group/test (should not mask any needed anomaly) # e.g. self._Mismatches['TestClassName'] = 300 # check base output class's checkTest() or sublcasses for any defaults self._Mismatches = dict() # custom color tolerances per group/test: 1 - 20 (0 default, 20 max) # (should not mask any needed anomaly) # e.g. self._ColorTols['TestClassName'] = 10 # check base output class's checkTest() or sublcasses for any defaults self._ColorTols = dict() # noinspection PyMethodMayBeStatic def checkTest(self, **kwargs): """Intended to be overridden in subclasses""" pass def test_default_label(self): # Default label placement, with text size in points self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_text_size_map_unit(self): # Label text size in map units format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_text_color(self): self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 # Label color change format = self.lyr.format() format.setColor(Qt.blue) self.lyr.setFormat(format) self.checkTest() def test_background_rect(self): self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 format = self.lyr.format() format.background().setEnabled(True) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 1 self.checkTest() def test_background_rect_w_offset(self): # Label rectangular background self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 # verify fix for issues # https://issues.qgis.org/issues/9057 # http://gis.stackexchange.com/questions/86900 format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setOffsetUnit(QgsUnitTypes.RenderMapUnits) format.background().setOffset(QPointF(-2900.0, -450.0)) self.lyr.setFormat(format) self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_background_svg(self): # Label SVG background format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setType(QgsTextBackgroundSettings.ShapeSVG) svg = os.path.join(svgSymbolsPath(), 'backgrounds', 'background_square.svg') format.background().setSvgFile(svg) format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) format.background().setSize(QSizeF(100.0, 0.0)) self.lyr.setFormat(format) self._Mismatches['TestComposerPdfVsComposerPoint'] = 580 self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_background_svg_w_offset(self): # Label SVG background format = self.lyr.format() format.setSizeUnit(QgsUnitTypes.RenderMapUnits) format.setSize(460) font = QFont(self._TestFont) format.setFont(font) format.background().setEnabled(True) format.background().setType(QgsTextBackgroundSettings.ShapeSVG) svg = os.path.join(svgSymbolsPath(), 'backgrounds', 'background_square.svg') format.background().setSvgFile(svg) format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) format.background().setSize(QSizeF(100.0, 0.0)) format.background().setOffsetUnit(QgsUnitTypes.RenderMapUnits) format.background().setOffset(QPointF(-2850.0, 500.0)) self.lyr.setFormat(format) self._Mismatches['TestComposerPdfVsComposerPoint'] = 760 self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_partials_labels_enabled(self): # Set Big font size format = self.lyr.format() font = QFont(self._TestFont) format.setFont(font) format.setSize(84) self.lyr.setFormat(format) # Enable partials labels engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, True) self._TestMapSettings.setLabelingEngineSettings(engine_settings) self._Mismatches['TestCanvasPoint'] = 779 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest() def test_partials_labels_disabled(self): # Set Big font size format = self.lyr.format() font = QFont(self._TestFont) format.setFont(font) format.setSize(84) self.lyr.setFormat(format) # Disable partials labels engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) self._TestMapSettings.setLabelingEngineSettings(engine_settings) self.checkTest() def test_buffer(self): # Label with buffer format = self.lyr.format() format.buffer().setEnabled(True) format.buffer().setSize(2) self.lyr.setFormat(format) self.checkTest() def test_shadow(self): # Label with shadow format = self.lyr.format() format.shadow().setEnabled(True) format.shadow().setOffsetDistance(2) format.shadow().setOpacity(1) self.lyr.setFormat(format) self.checkTest() def test_letter_spacing(self): # Modified letter spacing format = self.lyr.format() font = QFont(self._TestFont) font.setLetterSpacing(QFont.AbsoluteSpacing, 3.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest() def test_word_spacing(self): # Modified word spacing format = self.lyr.format() font = QFont(self._TestFont) font.setWordSpacing(20.5) format.setFont(font) format.setSize(30) self.lyr.setFormat(format) self.checkTest()
def get_style(self): """Get map styles. Get Fill color, label font, outline color. This function takes layer as input and configures style dictionary which is sent as HTTP request in order to adequatly represent map style on GIS Cloud. """ LOGGER.debug('Started map_styles function') if ISQGIS3: self.scale_pixels = \ iface.mapCanvas().mapSettings().outputDpi() / 72 else: self.scale_pixels = \ iface.mapCanvas().mapRenderer().outputDpi() / 72 self.unit_to_px = { "MM": 3.78 * self.scale_pixels, "Point": 1.33 * self.scale_pixels, "Inch": 96 * self.scale_pixels, # these two aren't yet supported by GC rendering, # so defaulting them to value of 1 px "MapUnit": None, "RenderMetersInMapUnits": None } layer_fromlevel = 0 layer_tolevel = 0 if self.qgis_layer.hasScaleBasedVisibility(): dpi = iface.mainWindow().physicalDpiX() max_scale_per_pixel = 156543.04 inches_per_meter = 39.37 factor = dpi * inches_per_meter * max_scale_per_pixel if self.qgis_layer.minimumScale() > 0: layer_fromlevel = int( round( math.log((factor / self.qgis_layer.minimumScale()), 2), 0)) if self.qgis_layer.maximumScale() > 0: layer_tolevel = int( round( math.log((factor / self.qgis_layer.maximumScale()), 2), 0)) if not ISQGIS3: # QGis2 has oposite logic with min/max scales # so we need to switch them (layer_tolevel, layer_fromlevel) = \ (layer_fromlevel, layer_tolevel) styles = [] tmp_dir = self.gc_api.qgis_api.tmp_dir if ISQGIS3: renderer = QgsRuleBasedRenderer.convertFromRenderer( self.qgis_layer.renderer()) else: renderer = QgsRuleBasedRendererV2.convertFromRenderer( self.qgis_layer.rendererV2()) for rule in renderer.rootRule().children(): symbol = rule.symbol() sym_size = 0 if self.layer.type[0] == "point": for layer_sym in symbol.symbolLayers(): temp_style = layer_sym.properties() self.convert_units_to_px(temp_style) if "size" in temp_style and \ float(temp_style["size"]) > sym_size: sym_size = float(temp_style["size"]) is_first_sym = True index = symbol.symbolLayerCount() while index > 0: index = index - 1 layer_sym = symbol.symbolLayer(index) temp_style = layer_sym.properties() self.convert_units_to_px(temp_style) val_label = None # in case of multiple symbolLayers() # labels should be set only once if is_first_sym: if ISQGIS3: if self.qgis_layer.labelsEnabled(): val_label = self.qgis_layer.labeling().settings() else: val_label = QgsPalLayerSettings() val_label.readFromLayer(self.qgis_layer) style = {} line_style = "line_style" line_width = 0 if self.layer.type[0] == "point": size = int(round(sym_size)) + 2 md5 = hashlib.md5() properties = str(temp_style) + self.dump_symbol_properties( layer_sym.subSymbol()) md5.update(properties.encode('utf-8')) symbol_file = "{}_{}.png".format(self.layer.id, md5.hexdigest()) style['iconsoverlap'] = 2 style['url'] = { "full_path": tmp_dir + '/' + symbol_file, "file": symbol_file, "symbol": symbol.clone(), "size": QSize(size, size) } elif self.layer.type[0] == "line": LOGGER.info('entered line_type part of function') LOGGER.info(temp_style) try: if u'line_color' in temp_style: style['color'] = ','.join( temp_style[u'line_color'].split(',')[0:3]) style['bordercolor'] = style['color'] if u'line_width' in temp_style: style['width'] = temp_style[u'line_width'] else: style['width'] = '1' line_width = float(style['width']) except Exception: LOGGER.info( 'Failed while mapping style for line vector layer', exc_info=True) if ('color' or 'bordercolor') not in style: style['color'] = '0,0,0' style['bordercolor'] = '0,0,0' LOGGER.info('Style is{}'.format(style)) # VectorPolygonLayer styles -> dashed line # and offset possibilities elif self.layer.type[0] == "polygon": line_style = "outline_style" has_border = not ("outline_style" in temp_style and temp_style["outline_style"] == "no") if layer_sym.layerType() == 'SimpleFill': if u'outline_color' in temp_style and has_border: style['bordercolor'] = \ ','.join( temp_style[u'outline_color'] .split(',')[0:3]) if u'outline_width' in temp_style and has_border: style['borderwidth'] = temp_style[u'outline_width'] if u'color' in temp_style and \ "style" in temp_style and \ temp_style["style"] == "solid": style['color'] = ','.join( temp_style[u'color'].split(',')[0:3]) elif layer_sym.layerType() == 'SimpleLine': if u'line_color' in temp_style: style['bordercolor'] = \ ','.join( temp_style[u'line_color'] .split(',')[0:3]) if u'line_width' in temp_style: style['line_width'] = temp_style[u'line_width'] elif u'color1' in temp_style: style['color'] = ','.join( temp_style[u'color1'].split(',')[0:3]) style['borderwidth'] = '1' if has_border: style['bordercolor'] = '0,0,0' else: style['bordercolor'] = '0,0,0' if has_border: style['borderwidth'] = '1' style['color'] = '0,0,0' if "borderwidth" in style: line_width = float(style['borderwidth']) if (layer_sym.layerType() != "SimpleFill" and layer_sym.layerType() != "SimpleLine") or \ ("style" in temp_style and not temp_style["style"] in ["solid", "no"]): if layer_sym.layerType() != "SimpleFill": temp_symbol = symbol.clone() tmp_sym_layer = temp_symbol.symbolLayer(index) while temp_symbol.symbolLayerCount() > 1: if temp_symbol.symbolLayer(0) == tmp_sym_layer: temp_symbol.deleteSymbolLayer(1) else: temp_symbol.deleteSymbolLayer(0) else: temp_style_hatch = temp_style.copy() temp_style_hatch["outline_style"] = "no" if ISQGIS3: temp_symbol = QgsFillSymbol.createSimple( temp_style_hatch) else: temp_symbol = QgsFillSymbolV2.createSimple( temp_style_hatch) properties = self.dump_symbol_properties(temp_symbol) md5 = hashlib.md5() md5.update(properties.encode('utf-8')) symbol_file = "{}_{}.png"\ .format(self.layer.id, md5.hexdigest()) style['hatchUrl'] = { "full_path": tmp_dir + '/' + symbol_file, "file": symbol_file, "symbol": temp_symbol, "size": QSize(64, 64) } if "use_custom_dash" in temp_style and \ temp_style["use_custom_dash"] == '1': style['dashed'] = temp_style[u'customdash'].replace( ';', ',') if ("dashed" not in style and line_style in temp_style and not temp_style[line_style] in ["solid", "no"]): process_dash_param(temp_style[line_style], line_width, style) if ISQGIS3: if val_label is not None: label_format = val_label.format() style['fontsize'] = label_format.size() style['labelfield'] = val_label.fieldName.lower() style['fontcolor'] = \ rgb_int2tuple(label_format.color().rgb()) if label_format.buffer().enabled(): style['outline'] = \ rgb_int2tuple( label_format.buffer().color().rgb()) if self.qgis_layer.geometryType() == 1: style['labelfield'] = '' style['textfield'] = val_label.fieldName.lower() if str(label_format.font().family()) in \ self.supported_fonts: style['fontname'] = label_format.font().family() else: style['fontname'] = 'Arial' LOGGER.info( ("Choosen font is not supported, " + "so every font style has been changed " + "to {0}").format(style['fontname'])) self.setup_label_offset(val_label, style) else: if val_label is not None and val_label.enabled: style['fontsize'] = val_label.textFont.pointSize() style['labelfield'] = val_label.fieldName.lower() style['fontcolor'] = rgb_int2tuple( val_label.textColor.rgb()) if val_label.bufferDraw: style['outline'] = rgb_int2tuple( val_label.bufferColor.rgb()) if self.qgis_layer.geometryType() == 1: style['labelfield'] = '' style['textfield'] = val_label.fieldName.lower() if str(val_label.textFont.family()) in \ self.supported_fonts: style['fontname'] = val_label.textFont.family() else: style['fontname'] = 'Arial' LOGGER.info("Choosen font is not supported, so " + "every font style has been changed " + " to {0}".format(style['fontname'])) self.setup_label_offset(val_label, style) if rule.filterExpression(): style['expression'] = rule.filterExpression().replace( '"', '') expression = self.qgis_layer.subsetString().replace('"', '') if expression and expression != '': if 'expression' in style and style['expression'] != '': style['expression'] = "(" + \ style['expression'] + \ ") AND (" + expression + ")" else: style['expression'] = expression if rule.label(): style['label'] = rule.label() style['showlabel'] = 't' \ if val_label is not None and \ 'labelfield' in style \ else 'f' style['visible'] = '1' if self.qgis_layer.hasScaleBasedVisibility(): factor = dpi * inches_per_meter * max_scale_per_pixel if ISQGIS3 and rule.minimumScale() > 0: style['fromlevel'] = \ int(round( math.log((factor / rule.minimumScale()), 2), 0)) elif layer_fromlevel > 0: style['fromlevel'] = layer_fromlevel if ISQGIS3 and rule.maximumScale() > 0: style['tolevel'] = \ int(round( math.log((factor / rule.maximumScale()), 2), 0)) elif layer_tolevel > 0: style['tolevel'] = layer_tolevel if 'borderwidth' in styles and \ style['borderwidth'] and \ float(style['borderwidth']) < 1: style['borderwidth'] = '1' key = "hatchUrl" if "hatchUrl" in style else "url" if key in style: asset = style[key] self.layer.assets.append(asset) LOGGER.info('URL for image upload: {}'.format( asset["file"])) style[key] = '/{}/qgis/map{}/{}'.format( self.gc_api.user.user_md5, self.gc_api.map.map_id, asset["file"]) styles.append(style) is_first_sym = False # all point styles are merged into one as we export the symbol # so it's not required to iterrate symbolLayers() if self.layer.type[0] == "point": break LOGGER.info('Styles function output {}'.format(styles)) LOGGER.debug('Finished map_styles function') return styles
def saveToLayer(self): units = self.unitDesignator() canvasCrs = self.canvas.mapSettings().destinationCrs() fields = QgsFields() fields.append(QgsField("label", QVariant.String)) fields.append(QgsField("value", QVariant.Double)) fields.append(QgsField("units", QVariant.String)) fields.append(QgsField("heading_to", QVariant.Double)) fields.append(QgsField("heading_from", QVariant.Double)) fields.append(QgsField("total_dist", QVariant.Double)) layer = QgsVectorLayer("LineString?crs={}".format(canvasCrs.authid()), "Measurements", "memory") dp = layer.dataProvider() dp.addAttributes(fields) layer.updateFields() num = len(self.capturedPoints) total = 0.0 for i in range(1, num): (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i]) total += distance total = self.unitDistance(total) for i in range(1, num): (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i]) pts = self.getLinePts(distance, self.capturedPoints[i - 1], self.capturedPoints[i]) distance = self.unitDistance(distance) feat = QgsFeature(layer.fields()) feat.setAttribute(0, "{:.2f} {}".format(distance, units)) feat.setAttribute(1, distance) feat.setAttribute(2, units) feat.setAttribute(3, startA) feat.setAttribute(4, endA) feat.setAttribute(5, total) feat.setGeometry(QgsGeometry.fromPolylineXY(pts)) dp.addFeatures([feat]) label = QgsPalLayerSettings() label.fieldName = 'label' try: label.placement = QgsPalLayerSettings.Line except Exception: label.placement = QgsPalLayerSettings.AboveLine format = label.format() format.setColor(settings.measureTextColor) format.setNamedStyle('Bold') label.setFormat(format) labeling = QgsVectorLayerSimpleLabeling(label) layer.setLabeling(labeling) layer.setLabelsEnabled(True) renderer = layer.renderer() renderer.symbol().setColor(settings.measureLineColor) renderer.symbol().setWidth(0.5) layer.updateExtents() QgsProject.instance().addMapLayer(layer)
def convert2CartoCSS(self, layer): """Convert layer symbology to CartoCSS""" renderer = layer.rendererV2() carto_css = '' label_css = '' label_settings = QgsPalLayerSettings() label_settings.readFromLayer(layer) if label_settings.enabled: d = { 'layername': '#' + layer.tableName(), 'field': label_settings.getLabelExpression().dump(), # TODO Get font size 'size': 11, 'color': label_settings.textColor.name() } filein = open(QgisCartoDB.CartoDBPlugin.PLUGIN_DIR + '/templates/labels.less') label_css = Template(filein.read()) label_css = label_css.substitute(d) # qDebug('Label CSS: ' + label_css) # CSS for single symbols if renderer.type() == 'singleSymbol': symbol = renderer.symbol() carto_css = self.symbol2CartoCSS(layer, symbol, '#' + layer.tableName()) # CSS for categorized symbols elif renderer.type() == 'categorizedSymbol': # qDebug('Categorized: ' + renderer.classAttribute()) for cat in renderer.categories(): symbol = cat.symbol() # qDebug("%s: %s type: %s" % (str(cat.value()), cat.label(), type(cat.value()))) if cat.value() is not None and cat.value() != '' and not isinstance(cat.value(), QPyNullVariant): if isinstance(cat.value(), (int, float, long)) or (isinstance(cat.value(), str) and cat.value().isdecimal()): value = unicode(cat.value()) else: value = unicode('"' + cat.value() + '"') value = str(value.encode('utf8', 'ignore')) # qDebug('Value {}'.format(value)) style_name = '#{}[{}={}]'.format(layer.tableName(), renderer.classAttribute(), value).decode('utf8') carto_css = carto_css + \ self.symbol2CartoCSS(layer, symbol, style_name) else: carto_css = self.symbol2CartoCSS(layer, symbol, '#' + layer.tableName()) + carto_css # CSS for graduated symbols elif renderer.type() == 'graduatedSymbol': # qDebug('Graduated') def upperValue(ran): """Get upper value from range""" return ran.upperValue() ranges = sorted(renderer.ranges(), key=upperValue, reverse=True) for ran in ranges: symbol = ran.symbol() ''' qDebug("%f - %f: %s" % ( ran.lowerValue(), ran.upperValue(), ran.label() )) ''' carto_css = carto_css + \ self.symbol2CartoCSS(layer, symbol, '#' + layer.tableName() + \ '[' + renderer.classAttribute() + '<=' + str(ran.upperValue()) + ']') return '/** Styles designed from QGISCartoDB Plugin */\n\n' + carto_css + '\n' + label_css
def save_pois_points(self, points, layername="Geopunt_poi", saveToFile=None, sender=None, startFolder=None ): attributes = [ QgsField("id", QVariant.Int), QgsField("thema", QVariant.String), QgsField("categorie", QVariant.String), QgsField("type", QVariant.String), QgsField("naam", QVariant.String), QgsField("telefoon", QVariant.String), QgsField("email", QVariant.String) , #address QgsField("straat", QVariant.String), QgsField("huisnr", QVariant.String), QgsField("busnr", QVariant.String), QgsField("postcode", QVariant.String), QgsField("gemeente", QVariant.String), QgsField("link", QVariant.String), QgsField("lastupdate", QVariant.String), QgsField("owner", QVariant.String) ] if not QgsProject.instance().mapLayer(self.poilayerid) : self.poilayer = QgsVectorLayer("Point", layername, "memory") self.poiProvider = self.poilayer.dataProvider() self.poiProvider.addAttributes(attributes) self.poilayer.updateFields() fields=self.poilayer.fields() for point in points: pt = QgsPointXY( point['location']['points'][0]['Point']['coordinates'][0], point['location']['points'][0]['Point']['coordinates'][1] ) poiId = point["id"] if "categories" in list(point.keys()) and len(point["categories"]) > 0: theme = point["categories"][0]['value'] else: theme = '' if "categories" in list(point.keys()) and len(point["categories"]) > 1: category = point["categories"][1]['value'] else: category = '' if "categories" in point and len(point["categories"]) > 2: poiType = point["categories"][2]['value'] else: poiType = '' name = point["labels"][0]["value"] if "phone" in list(point.keys()): phone = point["phone"] else: phone= "" if "email" in list(point.keys()): email = point["email"] else: email= "" #address if "address" in list(point['location'].keys()): if "street" in list(point['location']["address"].keys()): straat = point['location']["address"]["street"] else: straat = '' if "streetnumber" in list(point['location']["address"].keys()): huisnr = point['location']["address"]["streetnumber"] else: huisnr = '' if "boxnumber" in list(point['location']["address"].keys()): busnr = point['location']["address"]["boxnumber"] else: boxnr = '' postcode = point['location']["address"]["postalcode"] gemeente = point['location']["address"]["municipality"] else: straat = "" huisnr = "" busnr = "" postcode = "" gemeente = "" if "links" in point: link = point["links"][0]['href'] else: link = "" tijd = point["updated"] if "authors" in point: owner = point["authors"][0]["value"] else: owner= "" # add a feature fet = QgsFeature(fields) #set geometry fromCrs = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform( fromCrs, self.poilayer.crs(), QgsProject.instance() ) prjPt = xform.transform( pt ) fet.setGeometry(QgsGeometry.fromPointXY(prjPt)) fet['id'] = int( poiId ) fet['thema'] = theme fet['categorie'] = category fet['type'] = poiType fet['naam'] = name fet["email"] = email fet["telefoon"] = phone #address fet['straat'] = straat fet['huisnr'] = huisnr fet['busnr'] = busnr fet['postcode'] = postcode fet['gemeente'] = gemeente fet['link'] = link fet['lastupdate'] = tijd fet['owner'] = owner self.poiProvider.addFeatures([ fet ]) self.poilayer.updateExtents() if saveToFile and not QgsProject.instance().mapLayer(self.poilayerid): save = self._saveToFile( sender, startFolder ) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat(self.poilayer,fileName=fpath, fileEncoding="utf-8", driverName=flType ) if error == QgsVectorFileWriter.NoError: self.poilayer = QgsVectorLayer( fpath , layername, "ogr") self.poiProvider = self.poilayer.dataProvider() else: del self.poilayer, self.poiProvider raise Exception( msg ) else: del self.poilayer, self.poiProvider return # add Labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'naam' palyr.placement = QgsPalLayerSettings.Free self.poilayer.setLabelsEnabled(True) self.poilayer.setLabeling( QgsVectorLayerSimpleLabeling(palyr) ) # add layer if not already QgsProject.instance().addMapLayer(self.poilayer) # store layer id and refresh self.poilayerid = self.poilayer.id() self.canvas.refresh()
def save_pois_points(self, points, layername="Geopunt_poi", saveToFile=None, sender=None, startFolder=None): attributes = [ QgsField("id", QVariant.Int), QgsField("thema", QVariant.String), QgsField("categorie", QVariant.String), QgsField("type", QVariant.String), QgsField("naam", QVariant.String), QgsField("telefoon", QVariant.String), QgsField("email", QVariant.String), #address QgsField("straat", QVariant.String), QgsField("huisnr", QVariant.String), QgsField("busnr", QVariant.String), QgsField("postcode", QVariant.String), QgsField("gemeente", QVariant.String), QgsField("link", QVariant.String), QgsField("lastupdate", QVariant.String), QgsField("owner", QVariant.String) ] if not QgsProject.instance().mapLayer(self.poilayerid): self.poilayer = QgsVectorLayer("Point", layername, "memory") self.poiProvider = self.poilayer.dataProvider() self.poiProvider.addAttributes(attributes) self.poilayer.updateFields() fields = self.poilayer.fields() for point in points: pt = QgsPointXY( point['location']['points'][0]['Point']['coordinates'][0], point['location']['points'][0]['Point']['coordinates'][1]) poiId = point["id"] if "categories" in list( point.keys()) and len(point["categories"]) > 0: theme = point["categories"][0]['value'] else: theme = '' if "categories" in list( point.keys()) and len(point["categories"]) > 1: category = point["categories"][1]['value'] else: category = '' if "categories" in point and len(point["categories"]) > 2: poiType = point["categories"][2]['value'] else: poiType = '' name = point["labels"][0]["value"] if "phone" in list(point.keys()): phone = point["phone"] else: phone = "" if "email" in list(point.keys()): email = point["email"] else: email = "" #address if "address" in list(point['location'].keys()): if "street" in list(point['location']["address"].keys()): straat = point['location']["address"]["street"] else: straat = '' if "streetnumber" in list(point['location']["address"].keys()): huisnr = point['location']["address"]["streetnumber"] else: huisnr = '' if "boxnumber" in list(point['location']["address"].keys()): busnr = point['location']["address"]["boxnumber"] else: boxnr = '' postcode = point['location']["address"]["postalcode"] gemeente = point['location']["address"]["municipality"] else: straat = "" huisnr = "" busnr = "" postcode = "" gemeente = "" if "links" in point: link = point["links"][0]['href'] else: link = "" tijd = point["updated"] if "authors" in point: owner = point["authors"][0]["value"] else: owner = "" # add a feature fet = QgsFeature(fields) #set geometry fromCrs = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(fromCrs, self.poilayer.crs(), QgsProject.instance()) prjPt = xform.transform(pt) fet.setGeometry(QgsGeometry.fromPointXY(prjPt)) fet['id'] = int(poiId) fet['thema'] = theme fet['categorie'] = category fet['type'] = poiType fet['naam'] = name fet["email"] = email fet["telefoon"] = phone #address fet['straat'] = straat fet['huisnr'] = huisnr fet['busnr'] = busnr fet['postcode'] = postcode fet['gemeente'] = gemeente fet['link'] = link fet['lastupdate'] = tijd fet['owner'] = owner self.poiProvider.addFeatures([fet]) self.poilayer.updateExtents() if saveToFile and not QgsProject.instance().mapLayer(self.poilayerid): save = self._saveToFile(sender, startFolder) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat( self.poilayer, fileName=fpath, fileEncoding="utf-8", driverName=flType) if error == QgsVectorFileWriter.NoError: self.poilayer = QgsVectorLayer(fpath, layername, "ogr") self.poiProvider = self.poilayer.dataProvider() else: del self.poilayer, self.poiProvider raise Exception(msg) else: del self.poilayer, self.poiProvider return # add Labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'naam' palyr.placement = QgsPalLayerSettings.Free self.poilayer.setLabelsEnabled(True) self.poilayer.setLabeling(QgsVectorLayerSimpleLabeling(palyr)) # add layer if not already QgsProject.instance().addMapLayer(self.poilayer) # store layer id and refresh self.poilayerid = self.poilayer.id() self.canvas.refresh()
def setLabelFormatter(self, layer): # remove topicType try: palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) palyr.enabled = True palyr.fontBold = True palyr.shapeDraw = True palyr.shapeTransparency = 0 palyr.shapeType = QgsPalLayerSettings.ShapeRectangle palyr.textColor = QColor(255,255,255) # white palyr.placement = QgsPalLayerSettings.OverPoint palyr.quadOffset = QgsPalLayerSettings.QuadrantBelow palyr.multilineAlign = QgsPalLayerSettings.MultiCenter palyr.yOffset = 0.01 palyr.fieldName = '$format_label' palyr.writeToLayer(layer) Log.debug("Palyr Settings updated") except Exception as e: Log.debug("Error setting Label Format " + str(e))
def extract_layers(self, tree): """Return a list of RFU layers.""" # Create vector layers.. l_vertex = QgsVectorLayer(r"Point?crs=epsg:4326&index=yes", u"Sommet RFU", r"memory") l_edge = QgsVectorLayer(r"LineString?crs=epsg:4326&index=yes", u"Limite RFU", r"memory") p_vertex = l_vertex.dataProvider() p_edge = l_edge.dataProvider() # Define default style renderer.. renderer_vertex = QgsRuleBasedRendererV2(QgsMarkerSymbolV2()) vertex_root_rule = renderer_vertex.rootRule() vertex_rules = ( ((u"Borne, borne à puce, pierre, piquet, clou ou broche"), (u"$id >= 0 AND \"som_nature\" IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche')"), r"#EC0000", 2.2), ((u"Axe cours d'eau, axe fossé, haut de talus, pied de talus"), (u"$id >= 0 AND \"som_nature\" IN ('Axe cours d\'\'eau'," u"'Axe fossé', 'Haut de talus', 'Pied de talus')"), r"#EE8012", 2.2), ((u"Angle de bâtiment, axe de mur, angle de mur, " u"angle de clôture, pylône et toute autre valeur"), (u"$id >= 0 AND \"som_nature\" NOT IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche'," u"'Axe cours d\'\'eau', 'Axe fossé', 'Haut de talus'," u"'Pied de talus')"), r"#9784EC", 2.2), (u"Temporaire", r"$id < 0", "cyan", 2.4)) for label, expression, color, size in vertex_rules: rule = vertex_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setSize(size) vertex_root_rule.appendChild(rule) vertex_root_rule.removeChildAt(0) l_vertex.setRendererV2(renderer_vertex) renderer_edge = QgsRuleBasedRendererV2(QgsLineSymbolV2()) edge_root_rule = renderer_edge.rootRule() edge_rules = ((r"Limite", r"$id >= 0", "#0A0AFF", 0.5), (r"Temporaire", r"$id < 0", "cyan", 1)) for label, expression, color, width in edge_rules: rule = edge_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setWidth(width) edge_root_rule.appendChild(rule) edge_root_rule.removeChildAt(0) l_edge.setRendererV2(renderer_edge) # Add fields.. p_vertex.addAttributes([ QgsField(r"@id_noeud", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"som_ge_createur", QVariant.String), QgsField(r"som_nature", QVariant.String), QgsField(r"som_precision_rattachement", QVariant.Int), QgsField(r"som_coord_est", QVariant.Double), QgsField(r"som_coord_nord", QVariant.Double), QgsField(r"som_representation_plane", QVariant.String), # QgsField(r"date_creation", QVariant.Date) ]) p_edge.addAttributes([ QgsField(r"@id_arc", QVariant.Int), # QgsField(r"@id_noeud_debut", QVariant.Int), # QgsField(r"@id_noeud_fin", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"lim_ge_createur", QVariant.String), # QgsField(r"lim_date_creation", QVariant.Date) ]) # Add features from xml tree.. # ..to vertex layer.. fts_vertex = [] for e in tree.findall(r"sommet"): ft_vertex = QgsFeature() ft_vertex.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_noeud = int(e.attrib[r"id_noeud"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) som_ge_createur = unicode(e.find(r"./som_ge_createur").text) som_nature = unicode(e.find(r"./som_nature").text) som_prec_rattcht = int( e.find(r"./som_precision_rattachement").text) som_coord_est = float(e.find(r"./som_coord_est").text) som_coord_nord = float(e.find(r"./som_coord_nord").text) som_repres_plane = unicode( e.find(r"./som_representation_plane").text) # som_date_creation = QDate(datetime.strptime( # e.find(r"./som_date_creation").text, r"%Y-%m-%d").date()) ft_vertex.setAttributes([ _id_noeud, # _changeset, # _timestamp, _version, som_ge_createur, som_nature, som_prec_rattcht, som_coord_est, som_coord_nord, som_repres_plane, # som_date_creation ]) fts_vertex.append(ft_vertex) # ..to edge layer.. fts_edge = [] for e in tree.findall(r"limite"): ft_edge = QgsFeature() ft_edge.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_arc = int(e.attrib[r"id_arc"]) # _id_noeud_debut = int(e.attrib[r"id_noeud_debut"]) # _id_noeud_fin = int(e.attrib[r"id_noeud_fin"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) lim_ge_createur = unicode(e.find(r"./lim_ge_createur").text) # lim_date_creation = QDate(datetime.strptime( # e.find(r"./lim_date_creation").text, r"%Y-%m-%d").date()) ft_edge.setAttributes([ _id_arc, # _id_noeud_debut, # _id_noeud_fin, # _changeset, # _timestamp, _version, lim_ge_createur, # lim_date_creation ]) fts_edge.append(ft_edge) # Add features to layers.. p_vertex.addFeatures(fts_vertex) p_edge.addFeatures(fts_edge) # Update fields.. l_vertex.updateFields() l_edge.updateFields() # Update layer's extent.. l_vertex.updateExtents() l_edge.updateExtents() # Check if valid.. if not l_vertex.isValid() or not l_edge.isValid(): raise Exception( u"Une erreur est survenue lors du chargement de la couche.") # Set labelling... palyr = QgsPalLayerSettings() palyr.enabled = True # palyr.readFromLayer(l_vertex) palyr.fieldName = r"$id" # Expression $id palyr.placement = 1 # ::OverPoint palyr.quadOffset = 2 # ::QuadrantAboveRight palyr.setDataDefinedProperty(80, True, True, r"1", "") # ::OffsetUnits -> ::MM palyr.xOffset = 2.0 palyr.yOffset = -1.0 palyr.writeToLayer(l_vertex) # Then return layers.. return [l_vertex, l_edge]
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != "qgis_style": return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement("symbols") symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == "symbol": symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ "name": symbol_element.attribute("name"), "symbol": symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement("colorramps") ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == "colorramp": colorramp = QgsSymbolLayerUtils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ "name": ramp_element.attribute("name"), "colorramp": colorramp }) ramp_element = ramp_element.nextSiblingElement() # Get all the TextFormats - textformats - textformat self._textformats = [] textformats_element = document_element.firstChildElement("textformats") textformat_element = textformats_element.firstChildElement() while not textformat_element.isNull(): if textformat_element.tagName() == "textformat": textformat = QgsTextFormat() textformat.readXml(textformat_element, QgsReadWriteContext()) if textformat: self._textformats.append({ "name": textformat_element.attribute("name"), "textformat": textformat, }) textformat_element = textformat_element.nextSiblingElement() # Get all the LabelSettings - labelsettings - labelsetting - # QgsPalLayerSettings.readXML? self._labelsettings = [] labels_element = document_element.firstChildElement("labelsettings") label_element = labels_element.firstChildElement() while not label_element.isNull(): if label_element.tagName() == "labelsetting": labelsettings = QgsPalLayerSettings() labelsettings.readXml(label_element, QgsReadWriteContext()) if labelsettings: self._labelsettings.append({ "name": label_element.attribute("name"), "labelsettings": labelsettings, }) label_element = label_element.nextSiblingElement() return True
def test_AddPALToVectorLayer(self): """Check if we can set a label field, verify that PAL is assigned and that output is rendered correctly""" # TODO: add UTM PAL-specific shps, with 4326 as on-the-fly cross-check # setCanvasCrs(26913) myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') myVectorLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self._MapRegistry.addMapLayer(myVectorLayer) myLayers = QStringList() myLayers.append(myVectorLayer.id()) self._MapRenderer.setLayerSet(myLayers) self._MapRenderer.setExtent(myVectorLayer.extent()) self._Canvas.zoomToFullExtent() # check layer labeling is PAL with customProperty access # should not be activated on layer load myPalSet = myVectorLayer.customProperty("labeling").toString() myMessage = '\nExpected: Empty QString\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == '', myMessage # simulate clicking checkbox, setting label field and clicking apply self._testFont.setPointSize(20) myPalLyr = QgsPalLayerSettings() myPalLyr.enabled = True myPalLyr.fieldName = 'Name' myPalLyr.placement = QgsPalLayerSettings.Line myPalLyr.placementFlags = QgsPalLayerSettings.AboveLine myPalLyr.xQuadOffset = 0 myPalLyr.yQuadOffset = 0 myPalLyr.xOffset = 0 myPalLyr.yOffset = 0 myPalLyr.angleOffset = 0 myPalLyr.centroidWhole = False myPalLyr.textFont = self._testFont myPalLyr.textNamedStyle = QString("Medium") myPalLyr.textColor = Qt.black myPalLyr.textTransp = 0 myPalLyr.previewBkgrdColor = Qt.white myPalLyr.priority = 5 myPalLyr.obstacle = True myPalLyr.dist = 0 myPalLyr.scaleMin = 0 myPalLyr.scaleMax = 0 myPalLyr.bufferSize = 1 myPalLyr.bufferColor = Qt.white myPalLyr.bufferTransp = 0 myPalLyr.bufferNoFill = False myPalLyr.bufferJoinStyle = Qt.RoundJoin myPalLyr.formatNumbers = False myPalLyr.decimals = 3 myPalLyr.plusSign = False myPalLyr.labelPerPart = False myPalLyr.displayAll = True myPalLyr.mergeLines = False myPalLyr.minFeatureSize = 0.0 myPalLyr.vectorScaleFactor = 1.0 myPalLyr.rasterCompressFactor = 1.0 myPalLyr.addDirectionSymbol = False myPalLyr.upsidedownLabels = QgsPalLayerSettings.Upright myPalLyr.fontSizeInMapUnits = False myPalLyr.bufferSizeInMapUnits = False myPalLyr.labelOffsetInMapUnits = True myPalLyr.distInMapUnits = False myPalLyr.wrapChar = "" myPalLyr.preserveRotation = True myPalLyr.writeToLayer(myVectorLayer) # check layer labeling is PAL with customProperty access myPalSet = myVectorLayer.customProperty("labeling").toString() myMessage = '\nExpected: pal\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == 'pal', myMessage # check layer labeling is PAL via engine interface myMessage = '\nCould not get whether PAL enabled from labelingEngine' assert self._PalEngine.willUseLayer(myVectorLayer), myMessage # myChecker = QgsRenderChecker() myChecker.setControlName("expected_pal_aboveLineLabeling") myChecker.setMapRenderer(self._MapRenderer) myResult = myChecker.runTest("pal_aboveLineLabeling_python") myMessage = ('\nVector layer \'above line\' label engine ' 'rendering test failed') assert myResult, myMessage # compare against a straight rendering/save as from QgsMapCanvasMap # unnecessary? works a bit different than QgsRenderChecker, though # myImage = os.path.join(unicode(QDir.tempPath()), # 'render_pal_aboveLineLabeling.png') # self._Map.render() # self._Canvas.saveAsImage(myImage) # myChecker.setRenderedImage(myImage) # myResult = myChecker.compareImages("pal_aboveLineLabeling_python") # myMessage = ('\nVector layer \'above line\' label engine ' # 'comparison to QgsMapCanvasMap.render() test failed') # assert myResult, myMessage self._MapRegistry.removeMapLayer(myVectorLayer.id())
def extract_layers(self, tree): """Return a list of RFU layers.""" # Create vector layers.. l_vertex = QgsVectorLayer(r"Point?crs=epsg:4326&index=yes", u"Sommet RFU", r"memory") l_edge = QgsVectorLayer(r"LineString?crs=epsg:4326&index=yes", u"Limite RFU", r"memory") p_vertex = l_vertex.dataProvider() p_edge = l_edge.dataProvider() # Define default style renderer.. renderer_vertex = QgsRuleBasedRendererV2(QgsMarkerSymbolV2()) vertex_root_rule = renderer_vertex.rootRule() vertex_rules = ( ( (u"Borne, borne à puce, pierre, piquet, clou ou broche"), (u"$id >= 0 AND \"som_nature\" IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche')"), r"#EC0000", 2.2 ), ( (u"Axe cours d'eau, axe fossé, haut de talus, pied de talus"), (u"$id >= 0 AND \"som_nature\" IN ('Axe cours d\'\'eau'," u"'Axe fossé', 'Haut de talus', 'Pied de talus')"), r"#EE8012", 2.2 ), ( (u"Angle de bâtiment, axe de mur, angle de mur, " u"angle de clôture, pylône et toute autre valeur"), (u"$id >= 0 AND \"som_nature\" NOT IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche'," u"'Axe cours d\'\'eau', 'Axe fossé', 'Haut de talus'," u"'Pied de talus')"), r"#9784EC", 2.2 ), ( u"Temporaire", r"$id < 0", "cyan", 2.4 )) for label, expression, color, size in vertex_rules: rule = vertex_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setSize(size) vertex_root_rule.appendChild(rule) vertex_root_rule.removeChildAt(0) l_vertex.setRendererV2(renderer_vertex) renderer_edge = QgsRuleBasedRendererV2(QgsLineSymbolV2()) edge_root_rule = renderer_edge.rootRule() edge_rules = ((r"Limite", r"$id >= 0", "#0A0AFF", 0.5), (r"Temporaire", r"$id < 0", "cyan", 1)) for label, expression, color, width in edge_rules: rule = edge_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setWidth(width) edge_root_rule.appendChild(rule) edge_root_rule.removeChildAt(0) l_edge.setRendererV2(renderer_edge) # Add fields.. p_vertex.addAttributes([ QgsField(r"@id_noeud", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"som_ge_createur", QVariant.String), QgsField(r"som_nature", QVariant.String), QgsField(r"som_precision_rattachement", QVariant.Int), QgsField(r"som_coord_est", QVariant.Double), QgsField(r"som_coord_nord", QVariant.Double), QgsField(r"som_representation_plane", QVariant.String), # QgsField(r"date_creation", QVariant.Date) ]) p_edge.addAttributes([ QgsField(r"@id_arc", QVariant.Int), # QgsField(r"@id_noeud_debut", QVariant.Int), # QgsField(r"@id_noeud_fin", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"lim_ge_createur", QVariant.String), # QgsField(r"lim_date_creation", QVariant.Date) ]) # Add features from xml tree.. # ..to vertex layer.. fts_vertex = [] for e in tree.findall(r"sommet"): ft_vertex = QgsFeature() ft_vertex.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_noeud = int(e.attrib[r"id_noeud"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) som_ge_createur = unicode(e.find(r"./som_ge_createur").text) som_nature = unicode(e.find(r"./som_nature").text) som_prec_rattcht = int(e.find(r"./som_precision_rattachement").text) som_coord_est = float(e.find(r"./som_coord_est").text) som_coord_nord = float(e.find(r"./som_coord_nord").text) som_repres_plane = unicode(e.find(r"./som_representation_plane").text) # som_date_creation = QDate(datetime.strptime( # e.find(r"./som_date_creation").text, r"%Y-%m-%d").date()) ft_vertex.setAttributes([ _id_noeud, # _changeset, # _timestamp, _version, som_ge_createur, som_nature, som_prec_rattcht, som_coord_est, som_coord_nord, som_repres_plane, # som_date_creation ]) fts_vertex.append(ft_vertex) # ..to edge layer.. fts_edge = [] for e in tree.findall(r"limite"): ft_edge = QgsFeature() ft_edge.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_arc = int(e.attrib[r"id_arc"]) # _id_noeud_debut = int(e.attrib[r"id_noeud_debut"]) # _id_noeud_fin = int(e.attrib[r"id_noeud_fin"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) lim_ge_createur = unicode(e.find(r"./lim_ge_createur").text) # lim_date_creation = QDate(datetime.strptime( # e.find(r"./lim_date_creation").text, r"%Y-%m-%d").date()) ft_edge.setAttributes([ _id_arc, # _id_noeud_debut, # _id_noeud_fin, # _changeset, # _timestamp, _version, lim_ge_createur, # lim_date_creation ]) fts_edge.append(ft_edge) # Add features to layers.. p_vertex.addFeatures(fts_vertex) p_edge.addFeatures(fts_edge) # Update fields.. l_vertex.updateFields() l_edge.updateFields() # Update layer's extent.. l_vertex.updateExtents() l_edge.updateExtents() # Check if valid.. if not l_vertex.isValid() or not l_edge.isValid(): raise Exception(u"Une erreur est survenue lors du chargement de la couche.") # Set labelling... palyr = QgsPalLayerSettings() palyr.enabled = True # palyr.readFromLayer(l_vertex) palyr.fieldName = r"$id" # Expression $id palyr.placement = 1 # ::OverPoint palyr.quadOffset = 2 # ::QuadrantAboveRight palyr.setDataDefinedProperty(80, True, True, r"1", "") # ::OffsetUnits -> ::MM palyr.xOffset = 2.0 palyr.yOffset = -1.0 palyr.writeToLayer(l_vertex) # Then return layers.. return [l_vertex, l_edge]
def resultSelectedFeatureByRectTasDraw(self, geom, distance, direction_bearing): # flag = FlightPlanBaseSimpleDlg.btnConstruct_Click(self) # if not flag: # return if define._userLayers == None: mapUnits = define._canvas.mapUnits() constructionLayer = AcadHelper.createVectorLayer( "Lines", QGis.Line) AcadHelper.setGeometryAndAttributesInLayer( constructionLayer, geom.asPolyline(), False, {"Caption": str(round(distance, 4)) + "m"}) define._userLayers = constructionLayer palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(constructionLayer) QgisHelper.appendToCanvas(define._canvas, [constructionLayer], "Users layer", True) # self.resultLayerList = [constructionLayer] else: # constructionLayer = AcadHelper.createVectorLayer("Lines", QGis.Line) constructionLayer = define._userLayers iter = define._userLayers.getFeatures() equalFlag = 0 for feat in iter: # AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, feat) if geom.equals(feat.geometry()): equalFlag += 1 if equalFlag <= 0: AcadHelper.setGeometryAndAttributesInLayer( constructionLayer, geom.asPolyline(), False, {"Caption": str(round(distance, 4)) + "m"}) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(constructionLayer) # QgisHelper.appendToCanvas(define._canvas,[constructionLayer], "Users layer", True) # self.resultLayerList = [constructionLayer] QgisHelper.zoomToLayers([constructionLayer]) define._userLayers = constructionLayer pass
def utmGridlabelPlacer(self, root_rule, grid_spacing, extentsGeo, extentsUTM, px, py, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0, dy1, fSize, fontType, scale, geo_bb_or, layer_bound): if grid_spacing > 0: # Bottom ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings()) ruletest = self.utm_grid_labeler( ruletest, extentsUTM[0], extentsUTM[1], 0, extentsGeo[1], extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, 1, True, dx[0], dy[1], dy0[1], 0, 'UTMBotTest', fSize, fontType, grid_spacing, scale, range(1), geo_bb_or, layer_bound) rulechild = ruletest.children()[0] if rulechild.settings().fieldName == 'fail': rangeUD = range(2, UTM_num_x + 1) else: rangeUD = range(1, UTM_num_x + 1) for u in rangeUD: root_rule = self.utm_grid_labeler( root_rule, extentsUTM[0], extentsUTM[1], 0, extentsGeo[1], extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u, True, dx[0], dy[1], dy0[1] + 0.4 * (scale) * fSize / 1.5, 0, 'UTMBot' + str(u), fSize, fontType, grid_spacing, scale, rangeUD, geo_bb_or, layer_bound) # Upper rangeUD = range(1, UTM_num_x + 1) for u in rangeUD: root_rule = self.utm_grid_labeler( root_rule, extentsUTM[0], extentsUTM[3], 0, extentsGeo[3], extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u, True, dx[1], dy[0], dy0[0] - 1.3 * (scale) * fSize / 1.5, 0, 'UTMUp' + str(u), fSize, fontType, grid_spacing, scale, rangeUD, geo_bb_or, layer_bound) # Left ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings()) ruletest = self.utm_grid_labeler( ruletest, extentsUTM[0], extentsUTM[1], extentsGeo[0], 0, extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, 1, False, dx[2], dy[3], dy0[3], dy1[1], 'UTMLeftTest', fSize, fontType, grid_spacing, scale, range(1), geo_bb_or, layer_bound) rulechild = ruletest.children()[0] if rulechild.settings().fieldName == 'fail': rangeLat = range(2, UTM_num_y + 1) else: rangeLat = range(1, UTM_num_y + 1) for u in rangeLat: if u == min(rangeLat): extra_dist = -3.2 * scale * fSize / 1.5 else: extra_dist = 0 root_rule = self.utm_grid_labeler( root_rule, extentsUTM[0], extentsUTM[1], extentsGeo[0], 0, extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u, False, dx[2] + extra_dist, dy[3], dy0[3], dy1[1], 'UTMLeft' + str(u), fSize, fontType, grid_spacing, scale, rangeLat, geo_bb_or, layer_bound) # Right rangeLat = range(1, UTM_num_y + 1) for u in rangeLat: root_rule = self.utm_grid_labeler( root_rule, extentsUTM[2], extentsUTM[1], extentsGeo[2], 0, extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u, False, dx[3], dy[3], dy0[3], dy1[1], 'UTMRight' + str(1), fSize, fontType, grid_spacing, scale, rangeLat, geo_bb_or, layer_bound) return root_rule
def testCreateCalloutProperty(self): s = QgsAuxiliaryStorage() self.assertTrue(s.isValid()) # Create a new auxiliary layer with 'pk' as key vl = createLayer() pkf = vl.fields().field(vl.fields().indexOf('pk')) al = s.createAuxiliaryLayer(pkf, vl) self.assertTrue(al.isValid()) vl.setAuxiliaryLayer(al) # Create a new callout property on layer without labels key = QgsCallout.DestinationX index = QgsAuxiliaryLayer.createProperty(key, vl) self.assertEqual(index, -1) # Labeling, but no callouts settings = QgsPalLayerSettings() settings.setCallout(None) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) index = QgsAuxiliaryLayer.createProperty(key, vl) self.assertEqual(index, -1) # callouts settings = QgsPalLayerSettings() callout = QgsSimpleLineCallout() callout.setEnabled(True) settings.setCallout(callout) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) index = QgsAuxiliaryLayer.createProperty(key, vl) p = QgsCallout.propertyDefinitions()[key] afName = QgsAuxiliaryLayer.nameFromProperty(p, True) afIndex = vl.fields().indexOf(afName) self.assertEqual(index, afIndex) settings = vl.labeling().settings() self.assertEqual( settings.callout().dataDefinedProperties().property(key), QgsProperty.fromField('auxiliary_storage_callouts_destinationx')) key2 = QgsCallout.DestinationY index = QgsAuxiliaryLayer.createProperty(key2, vl) p = QgsCallout.propertyDefinitions()[key2] afName = QgsAuxiliaryLayer.nameFromProperty(p, True) afIndex = vl.fields().indexOf(afName) self.assertEqual(index, afIndex) settings = vl.labeling().settings() self.assertEqual( settings.callout().dataDefinedProperties().property(key), QgsProperty.fromField('auxiliary_storage_callouts_destinationx')) self.assertEqual( settings.callout().dataDefinedProperties().property(key2), QgsProperty.fromField('auxiliary_storage_callouts_destinationy'))
def getLabels(layer, safeLayerName, outputProjectFileName): label_exp = '' labeltext = "" f = '' palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) if palyr.enabled and palyr.fieldName and palyr.fieldName != "": bgColor = palyr.shapeFillColor.name() borderWidth = palyr.shapeBorderWidth borderColor = palyr.shapeBorderColor.name() x = palyr.shapeSize.x() y = palyr.shapeSize.y() font = palyr.textFont fontSize = font.pointSize() fontFamily = font.family() fontItalic = font.italic() fontBold = font.bold() fontColor = palyr.textColor.name() fontUnderline = font.underline() xOffset = palyr.xOffset yOffset = palyr.yOffset styleStart = "'<div style=\"color: %s; font-size: %dpt; " % (fontColor, fontSize) if palyr.shapeDraw: styleStart += "background-color: %s; " % bgColor styleStart += "border: %dpx solid %s; " % (borderWidth, borderColor) if palyr.shapeSizeType == 0: styleStart += "padding: %dpx %dpx; " % (y, x) if palyr.shapeSizeType == 1: styleStart += "width: %dpx; " % x styleStart += "height: %dpx; " % y if fontBold: styleStart += "font-weight: bold; " if fontItalic: styleStart += "font-style: italic; " styleStart += "font-family: \\'%s\\', sans-serif;\">' + " % fontFamily styleEnd = " + '</div>'" if palyr.isExpression and palyr.enabled: exprFilename = os.path.join(outputProjectFileName, "js", "qgis2web_expressions.js") name = compile_to_file(palyr.getLabelExpression(), "label_%s" % safeLayerName, "Leaflet", exprFilename) js = "%s(context)" % (name) js = js.strip() f = js else: fn = palyr.fieldName f = "layer.feature.properties['%s']" % handleHiddenField(layer, fn) labeltext = ".bindTooltip((" + unicode(f) labeltext += " !== null?String(%s%s)%s:'')" % (styleStart, unicode(f), styleEnd) labeltext += ", {permanent: true, offset: [-0, -16], " labeltext += "className: 'css_%s'}" % safeLayerName labeltext += ").openTooltip();" labeltext = """ layer_%s.eachLayer(function(layer) { layer%s });""" % (safeLayerName, labeltext) else: labeltext = "" return labeltext