def onResultTableSelChanged(self): cur_row_index = self.dockWidget.tableResult.currentRow() if cur_row_index > -1: self.clearHighlight(self.intersected_h_list) self.clearHighlight(self.intersection_h_list) f_geometry = QgsGeometry() f_geometry = QgsGeometry.fromWkt( self.dockWidget.tableResult.item(cur_row_index, 1).text()) h = QgsHighlight(self.iface.mapCanvas(), f_geometry, self.inters_layer) h.setColor(QColor(26, 200, 0, 220)) h.setWidth(6) h.setFillColor(QColor(26, 200, 0, 150)) self.intersected_h_list.append(h) if_geometry = QgsGeometry() if_geometry = QgsGeometry.fromWkt( self.dockWidget.tableResult.item(cur_row_index, 2).text()) ih = QgsHighlight(self.iface.mapCanvas(), if_geometry, self.inters_layer) ih.setColor(QColor(230, 0, 0, 220)) ih.setWidth(6) ih.setFillColor(QColor(230, 0, 0, 150)) self.intersection_h_list.append(ih)
def highlight_features(self): for item in self.highlight: self.canvas.scene().removeItem(item) del self.highlight[:] del self.highlight_rows[:] index = self.tabWidget.currentIndex() tab = self.tabWidget.widget(index) if self.tabWidget.count() != 0: table = self.tabWidget.widget(index).findChildren(QTableWidget)[0] nb = 0 area = 0 length = 0 items = table.selectedItems() for item in items: if item.row() not in self.highlight_rows: if self.selectGeom: highlight = QgsHighlight(self.canvas, item.feature.geometry(), self.tabWidget.widget(index).layer) else: highlight = QgsHighlight(self.canvas, item.feature.geometry().centroid(), self.tabWidget.widget(index).layer) highlight.setColor(QColor(255,0,0)) self.highlight.append(highlight) self.highlight_rows.append(item.row()) g = QgsGeometry(item.feature.geometry()) g.transform(QgsCoordinateTransform(tab.layer.crs(), QgsCoordinateReferenceSystem(2154), QgsProject.instance())) # geometry reprojection to get meters nb += 1 area += g.area() length += g.length() if tab.layer.geometryType()==QgsWkbTypes.PolygonGeometry: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb)+' '+self.tr('Area')+': '+"%.2f"%area+' m'+u'²') elif tab.layer.geometryType()==QgsWkbTypes.LineGeometry: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb)+' '+self.tr('Length')+': '+"%.2f"%length+' m') else: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb))
def onIdentified(self, selected_layer, selected_feature): selected_type = "" if self.application_settings.get_layers_route_node_name( ) == selected_layer.sourceName(): selected_type = self.application_settings.get_types_route_node() elif self.application_settings.get_layers_route_segment_name( ) == selected_layer.sourceName(): selected_type = self.application_settings.get_types_route_segment() else: self.identifyHighlight.hide() return if self.identifyHighlight is not None: self.identifyHighlight.hide() color = QColor(0, 255, 0) self.identifyHighlight = QgsHighlight(self.iface.mapCanvas(), selected_feature.geometry(), selected_layer) self.identifyHighlight.setWidth(3) self.identifyHighlight.setColor(color) self.identifyHighlight.show() mrid = selected_feature.attribute("mrid") self.last_identified_feature_mrid = mrid self.last_identified_feature_type = selected_type if selected_type != "": self.identifyNetworkElementHandler.handle(mrid, selected_type)
def highlightReferencingFeature(self): self.deleteHighlight() if not self.relation.isValid() or not self.referencingFeature.isValid( ): return self.featureHighlight = QgsHighlight( self.iface.mapCanvas(), self.referencingFeature.geometry(), self.relation.referencingLayer()) settings = QSettings() color = QColor( settings.value("/Map/highlight/color", QGis.DEFAULT_HIGHLIGHT_COLOR.name())) alpha = int( settings.value("/Map/highlight/colorAlpha", QGis.DEFAULT_HIGHLIGHT_COLOR.alpha())) bbuffer = float( settings.value("/Map/highlight/buffer", QGis.DEFAULT_HIGHLIGHT_BUFFER_MM)) minWidth = float( settings.value("/Map/highlight/minWidth", QGis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM)) self.featureHighlight.setColor(color) color.setAlpha(alpha) self.featureHighlight.setFillColor(color) self.featureHighlight.setBuffer(bbuffer) self.featureHighlight.setMinWidth(minWidth) self.featureHighlight.show() timer = QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.deleteHighlight) timer.start(3000)
def highlight_spatial_unit( self, spatial_unit, geom, map_canvas ): layer = self._iface.activeLayer() map_canvas.setExtent(layer.extent()) map_canvas.refresh() if self.spatial_unit_layer(spatial_unit, layer): self.clear_sel_highlight() qgis_geom = qgsgeometry_from_wkbelement(geom) self.sel_highlight = QgsHighlight( map_canvas, qgis_geom, layer ) rgba = selection_color() self.sel_highlight.setFillColor(rgba) self.sel_highlight.setWidth(3) self.sel_highlight.show() extent = qgis_geom.boundingBox() extent.scale(1.5) map_canvas.setExtent(extent) map_canvas.refresh() else: return
def runTestForLayer(self, layer, testname): tempdir = tempfile.mkdtemp() layer = QgsVectorLayer(layer, 'Layer', 'ogr') QgsProject.instance().addMapLayer(layer) self.iface.mapCanvas().setExtent(layer.extent()) geom = next(layer.getFeatures()).geometry() highlight = QgsHighlight(self.iface.mapCanvas(), geom, layer) color = QColor(Qt.red) highlight.setColor(color) highlight.setWidth(2) color.setAlpha(50) highlight.setFillColor(color) highlight.show() image = QImage(QSize(400, 400), QImage.Format_ARGB32) image.fill(Qt.white) painter = QPainter() painter.begin(image) self.iface.mapCanvas().render(painter) painter.end() control_image = os.path.join(tempdir, 'highlight_{}.png'.format(testname)) image.save(control_image) checker = QgsRenderChecker() checker.setControlPathPrefix("highlight") checker.setControlName("expected_highlight_{}".format(testname)) checker.setRenderedImage(control_image) self.assertTrue(checker.compareImages("highlight_{}".format(testname))) shutil.rmtree(tempdir)
def highlight_feature(self, canvas_extent=CanvasExtent.Fixed): if self.canvas is None or not self.feature.isValid(): return geom = self.feature.geometry() if geom is None: return if canvas_extent == CanvasExtent.Scale: feature_bounding_box = geom.boundingBox() feature_bounding_box = self.canvas.mapSettings( ).layerToMapCoordinates(self.layer, feature_bounding_box) extent = self.canvas.extent() if not extent.contains(feature_bounding_box): extent.combineExtentWith(feature_bounding_box) extent.scale(1.1) self.canvas.setExtent(extent) self.canvas.refresh() elif canvas_extent == CanvasExtent.Pan: centroid = geom.centroid() center = centroid.asPoint() center = self.canvas.mapSettings().layerToMapCoordinates( self.layer, center) self.canvas.zoomByFactor(1.0, center) # refresh is done in this method # highlight self.delete_highlight() self.highlight = QgsHighlight(self.canvas, geom, self.layer) settings = QSettings() color = QColor( settings.value("/Map/highlight/color", Qgis.DEFAULT_HIGHLIGHT_COLOR.name())) alpha = int( settings.value("/Map/highlight/colorAlpha", Qgis.DEFAULT_HIGHLIGHT_COLOR.alpha())) buffer = 2 * float( settings.value("/Map/highlight/buffer", Qgis.DEFAULT_HIGHLIGHT_BUFFER_MM)) min_width = 2 * float( settings.value("/Map/highlight/min_width", Qgis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM)) self.highlight.setColor(color) # sets also fill with default alpha color.setAlpha(alpha) self.highlight.setFillColor(color) # sets fill with alpha self.highlight.setBuffer(buffer) self.highlight.setMinWidth(min_width) self.highlight.setWidth(4.0) self.highlight.show() self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.timeout.connect(self.delete_highlight) self.timer.start(3000)
def highlightFeature(self, theFeature): highlight = QgsHighlight(self.mTheCanvas, theFeature.geometry(), self.mTheLayer) highlight.setColor(QColor(255,0,0,128)) highlight.setFillColor(QColor(255,0,0,128)) highlight.setBuffer(0.5) highlight.setMinWidth(6) highlight.setWidth(6) highlight.show() self.highlightList.append(highlight) return
def highlightByGeometry(self, geometry, color=QColor(255, 0, 0, 128)): highlight = QgsHighlight(self.mTheCanvas, geometry, self.mTheLayer) highlight.setColor(color) highlight.setFillColor(color) highlight.setBuffer(0.5) highlight.setMinWidth(6) highlight.setWidth(6) highlight.show() self.highlightList.append(highlight) return
def highlight(self, error, crs): self.clearHighlight() if not error: return # QgsHighlight does reprojection from layer CRS layer = QgsVectorLayer('Point?crs=' + crsString(crs), 'LRS error highlight', 'memory') self.errorHighlight = QgsHighlight(self.mapCanvas, error.geo, layer) # highlight point size is hardcoded in QgsHighlight self.errorHighlight.setWidth(2) self.errorHighlight.setColor(Qt.yellow) self.errorHighlight.show()
def markFeature(self, lay, feat): try: color = QColor(Qt.red) highlight = QgsHighlight(self.iface.mapCanvas(), feat, lay) highlight.setColor(color) color.setAlpha(50) highlight.setFillColor(color) highlight.show() return highlight except Exception as e: self.info.err(e)
def on_chooseId_currentIndexChanged(self, thisIndex): self.clearHighlight() aPkValue = self.chooseId.currentText() aGeom = self.featDict[self.pkValues[aPkValue]].geometry() hlColor, hlFillColor, hlBuffer, hlMinWidth = dtGetHighlightSettings() self.hl = QgsHighlight(self.iface.mapCanvas(), aGeom, self.editLayer) self.hl.setColor(hlColor) self.hl.setFillColor(hlFillColor) self.hl.setBuffer(hlBuffer) self.hl.setWidth(hlMinWidth) self.hl.show()
def multi_select_highlight(self, index): """ Highlights a feature with rubberBald class when selecting features are more than one. :param index: Selected QTreeView item index :type Integer :return: None """ map = self.iface.mapCanvas() try: # Get the selected item text using the index selected_item = self.model.itemFromIndex(index) # Use mutli-select only when more than 1 items are selected. if self.layer.selectedFeatures() < 2: return self.selected_root = selected_item # Split the text to get the key and value. selected_item_text = selected_item.text() selected_value = selected_item.data() # If the first word is feature, expand & highlight. if selected_item_text == format_name(self.spatial_unit.short_name): self.view.expand(index) # expand the item # Clear any existing highlight self.clear_sel_highlight() # Insert highlight # Create expression to target the selected feature expression = QgsExpression( "\"id\"='" + str(selected_value) + "'" ) # Get feature iteration based on the expression ft_iteration = self.layer.getFeatures( QgsFeatureRequest(expression) ) # Retrieve geometry and attributes for feature in ft_iteration: # Fetch geometry geom = feature.geometry() self.sel_highlight = QgsHighlight(map, geom, self.layer) self.sel_highlight.setFillColor(selection_color()) self.sel_highlight.setWidth(4) self.sel_highlight.setColor(QColor(212,95,0, 255)) self.sel_highlight.show() break except AttributeError: # pass attribute error on child items such as party pass except IndexError: pass
def setHighlight(self, ly, vertex): if self.highlight: self.highlight.hide() self.highlight = None if vertex: color = QColor(255, 0, 100, 255) lv = vertex + [vertex[0]] g = QgsGeometry.fromPolyline(lv).convertToType(2) print(g.asWkt(3)) self.highlight = QgsHighlight(self.iface.mapCanvas(), g, ly) self.highlight.setColor(color) self.highlight.setWidth(5) color.setAlpha(50) self.highlight.setFillColor(color) self.highlight.show()
def test_feature_transformation(self): poly_shp = os.path.join(TEST_DATA_DIR, 'polys.shp') layer = QgsVectorLayer(poly_shp, 'Layer', 'ogr') sub_symbol = QgsFillSymbol.createSimple({ 'color': '#8888ff', 'outline_style': 'no' }) sym = QgsFillSymbol() buffer_layer = QgsGeometryGeneratorSymbolLayer.create( {'geometryModifier': 'buffer($geometry, -0.4)'}) buffer_layer.setSymbolType(QgsSymbol.Fill) buffer_layer.setSubSymbol(sub_symbol) sym.changeSymbolLayer(0, buffer_layer) layer.setRenderer(QgsSingleSymbolRenderer(sym)) canvas = QgsMapCanvas() canvas.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:3857')) canvas.setFrameStyle(0) canvas.resize(600, 400) self.assertEqual(canvas.width(), 600) self.assertEqual(canvas.height(), 400) canvas.setLayers([layer]) canvas.setExtent(QgsRectangle(-11960254, 4247568, -11072454, 4983088)) canvas.show() # need to wait until first redraw can occur (note that we first need to wait till drawing starts!) while not canvas.isDrawing(): app.processEvents() canvas.waitWhileRendering() feature = layer.getFeature(1) self.assertTrue(feature.isValid()) highlight = QgsHighlight(canvas, feature, layer) color = QColor(Qt.red) highlight.setColor(color) color.setAlpha(50) highlight.setFillColor(color) highlight.show() highlight.show() self.assertTrue( self.canvasImageCheck('highlight_transform', 'highlight_transform', canvas))
def highlight_courant(self): """highlight animated flowline layer where Courant number is higher than a given value (use velocity variable as flowline-results)""" if len(QgsProject.instance().mapLayersByName("line_results")) == 0: self.iface.messageBar().pushMessage( "Warning", 'Couldn\'t find line_results layer, click "Animation on" button', level=Qgis.Warning, ) return # layer found canvas = self.iface.mapCanvas() line_results = QgsProject.instance().mapLayersByName("line_results")[0] global_settings_layer = QgsProject.instance().mapLayersByName( "v2_global_settings" )[0] timestep = list(global_settings_layer.getFeatures())[0][ "sim_time_step" ] # [0] -> [self.selected_scenario_index] d = QgsDistanceArea() d.setEllipsoid("WGS84") features = line_results.getFeatures() for feature in features: kcu = feature["kcu"] if kcu in [0, 1, 2, 3, 5, 100, 101]: geometry = feature.geometry() length = d.measureLength(geometry) velocity = abs(feature["result"]) courant = velocity * timestep / length if courant > self.courantThreshold.value(): color = QtGui.QColor(Qt.red) highlight = QgsHighlight(canvas, feature, line_results) highlight.setColor(color) highlight.setMinWidth(courant / 2) # highlight.setBuffer() color.setAlpha(50) highlight.setFillColor(color) highlight.show() self.highlights.append(highlight)
def onMapClickedTableSelChanged(self): cur_row_index = self.map_clicked_dlg.tableClickedWays.currentRow() if cur_row_index > -1: self.clearAllHighlights() f_geometry = QgsGeometry() f_geometry = QgsGeometry.fromWkt( self.map_clicked_dlg.tableClickedWays.item(cur_row_index, 1).text()) h = QgsHighlight(self.iface.mapCanvas(), f_geometry, self.current_layer) h.setColor(QColor(0, 15, 183, 220)) h.setWidth(6) h.setFillColor(QColor(0, 15, 183, 150)) self.mapclicked_h_list.append(h) self.setButtonOkStatus()
def _addHighlight(self, canvas, geometry, layer): hl = QgsHighlight(canvas, geometry, layer) color = QColor(QSettings().value('/Map/highlight/color', QGis.DEFAULT_HIGHLIGHT_COLOR.name(), str)) alpha = QSettings().value('/Map/highlight/colorAlpha', QGis.DEFAULT_HIGHLIGHT_COLOR.alpha(), int) buff = QSettings().value('/Map/highlight/buffer', QGis.DEFAULT_HIGHLIGHT_BUFFER_MM, float) minWidth = QSettings().value('/Map/highlight/minWidth', QGis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM, float) hl.setColor(color) color.setAlpha(alpha) hl.setFillColor(color) hl.setBuffer(buff) hl.setMinWidth(minWidth) self._highlights.append(hl)
def setCurrentStation(self, feature): """ set the panel's current prediction station to the one described by the given feature """ self.stationFeature = feature self.stationZone = stationTimeZone(feature) self.stationLabel.setText(feature['name']) self.updateTime() self.updateStationLink() self.loadStationPredictions() if self.stationHighlight is not None: self.stationHighlight.hide() self.stationHighlight = QgsHighlight(self.canvas, self.stationFeature, self.currentStationsLayer) self.stationHighlight.setColor(QColor(Qt.red)) self.stationHighlight.setFillColor(QColor(Qt.red)) self.stationHighlight.show()
def handle(self, message): if message.username != self.settings.get_user_name_prefix(): return for highlight in self.highlightFeatures: self.iface.mapCanvas().scene().removeItem(highlight) self.highlightFeatures = [] if len(message.identifiedFeatureMrids) == 0: return layer = None if message.featureType == self.settings.get_types_route_segment(): layer = QgsProject.instance().mapLayersByName( self.settings.get_layers_route_segment_name())[0] elif message.featureType == self.settings.get_types_route_node(): layer = QgsProject.instance().mapLayersByName( self.settings.get_layers_route_node_name())[0] filterExpression = "" for i in range(len(message.identifiedFeatureMrids)): mrid = message.identifiedFeatureMrids[i] if i == len(message.identifiedFeatureMrids) - 1: filterExpression += f'"mrid" = \'{mrid}\'' else: filterExpression += f'"mrid" = \'{mrid}\' OR ' features = layer.getFeatures( QgsFeatureRequest().setFilterExpression(filterExpression)) color = QColor(64, 224, 208) for feature in features: identifyHighlight = QgsHighlight(self.iface.mapCanvas(), feature.geometry(), layer) identifyHighlight.setWidth(5) identifyHighlight.setColor(color) self.highlightFeatures.append(identifyHighlight) for highlight in self.highlightFeatures: highlight.show() layer.triggerRepaint()
def highlightLocatePoint(self): # #debug ('highlightLocatePoint') self.clearLocateHighlight() if not self.locatePoint: return if not self.locateHighlightCheckBox.isChecked(): return mapCanvas = self.iface.mapCanvas() mapSettings = mapCanvas.mapSettings() # QgsHighlight does reprojection from layer CRS crs = getProjectCrs() if isProjectCrsEnabled() else self.lrsLayer.crs layer = QgsVectorLayer('Point?crs=' + crsString(crs), 'LRS locate highlight', 'memory') #self.locateHighlight = QgsHighlight(mapCanvas, QgsGeometry.fromPoint(self.locatePoint), layer) # QgsGeometry(QgsPoint) takes ownership! self.locateHighlight = QgsHighlight( mapCanvas, QgsGeometry(QgsPoint(self.locatePoint)), layer) # highlight point size is hardcoded in QgsHighlight self.locateHighlight.setWidth(2) self.locateHighlight.setColor(Qt.yellow) self.locateHighlight.show()
def testBugfix48471(self): """ Test scenario of https://github.com/qgis/QGIS/issues/48471 """ lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp') layer = QgsVectorLayer(lines_shp, 'Layer', 'ogr') QgsProject.instance().addMapLayer(layer) self.iface.mapCanvas().setExtent(layer.extent()) geom = next(layer.getFeatures()).geometry() highlight = QgsHighlight(self.iface.mapCanvas(), geom, layer) highlight.setBuffer(12345) try: found = False for item in self.iface.mapCanvas().scene().items(): if isinstance(item, QgsHighlight): if item.buffer() == 12345: found = True self.assertTrue(found) finally: self.iface.mapCanvas().scene().removeItem(highlight)
pr.addAttributes([ QgsField("name", QVariant.String), QgsField("age", QVariant.Int), QgsField("size", QVariant.Double) ]) vl.updateFields() # tell the vector layer to fetch changes from the provider infos = [[10, 10, "John", 24, 1.73], [40, -60, "Paul", 29, 1.86], [60, 5, "George", 34, 1.69], [0, 45, "Ringo", 73, 1.75]] # add features for i in infos: fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(i[0], i[1]))) fet.setAttributes(i[2:5]) pr.addFeatures([fet]) # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer vl.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(vl) highlight = QgsHighlight(iface.mapCanvas(), QgsGeometry.fromPoint(QgsPoint(0, 47)), vl) highlight.setBuffer(1.5) highlight.setColor(QColor('black')) highlight.setFillColor(QColor('blue')) highlight.setWidth(0.5) iface.mapCanvas().refresh()