def add_symbology(self): categories = [] for lisaCategory, (color, label) in list(self.lisa.items()): sym = QgsSymbol.defaultSymbol(self.output_layer.geometryType()) sym.setColor(QColor(color)) category = QgsRendererCategory(lisaCategory, sym, label) categories.append(category) self.newlayer = QgsVectorLayer( self.output_layer.source(), self.output_layer.name() + " significance test", self.output_layer.providerType()) self.output_layer.setOpacity(0.4) QgsProject.instance().addMapLayer(self.newlayer) # noinspection PyArgumentList renderer = QgsCategorizedSymbolRenderer('LISA_Q', categories) self.output_layer.setRenderer(renderer) symbol = QgsSymbol.defaultSymbol( QgsWkbTypes.geometryType(QgsWkbTypes.Polygon)) color_ramp = QgsGradientColorRamp(QColor(0, 0, 0), QColor(255, 0, 0)) # noinspection PyArgumentList renderer = QgsGraduatedSymbolRenderer.createRenderer( self.newlayer, 'LISA_C', 4, QgsGraduatedSymbolRenderer.Jenks, symbol, color_ramp) self.newlayer.setRenderer(renderer) #The input val of seOPacity is 0-1 not 0-100 as setLyerTransvarency #https://gis.stackexchange.com/questions/150858/setting-transparency-of-layer-group-with-python-in-qgis self.newlayer.setOpacity(0.4)
def postProcessLayer(self, layer, context, feedback): """Run the coloring process""" _ = context layer_type = layer.wkbType() feedback.pushInfo('Creating the style from OSM data "colour".') index = self.fields.index('colour') if index != -1: colors = layer.uniqueValues(index) categories = [] for value in colors: if str(value) == 'None': value = '' if layer_type in [self.layer_type_dict['lines'], self.layer_type_dict['multilinestrings']]: symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.LineGeometry) elif layer_type == self.layer_type_dict['point']: symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) elif layer_type == self.layer_type_dict['multipolygons']: symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PolygonGeometry) else: break symbol.setColor(QColor(value)) category = QgsRendererCategory(str(value), symbol, str(value)) categories.append(category) renderer = QgsCategorizedSymbolRenderer("colour", categories) layer.setRenderer(renderer) layer.triggerRepaint()
def __init__(self, Layer, hinderAttr='hinder'): '1: in hinderAttr is veel hinder, 0: in hinderAttr is weinig hinder' hinderSymbol = QgsSymbol.defaultSymbol( 0 ) #0=point noHinderSymbol = QgsSymbol.defaultSymbol( 0 ) #Layer.geometryType() hinderSymbol.setColor(QColor('#FF0000')) noHinderSymbol.setColor(QColor('#FFFF00')) noHinder= QgsRendererCategory(0, noHinderSymbol ,'weinig hinder') hinder= QgsRendererCategory(1, hinderSymbol ,'veel hinder') self.render = QgsCategorizedSymbolRenderer(hinderAttr,[noHinder,hinder])
def load_file_as_layer(file_name, layer_name, group_name=None, min_val=None, max_val=None, mean_val=None, value_color=None, area=None, attribute=None): layer = QgsRasterLayer(file_name, layer_name) if layer.isValid(): # generate legend with min/max values create_legend(layer, max_val, min_val, mean_val, value_color, area) else: layer = QgsVectorLayer(file_name, layer_name) # add_id_attribute_to_layer(layer) if layer.isValid(): renderer = layer.renderer() print(layer.geometryType()) if renderer and layer.geometryType() == 2: # make fill of shapes invisible mySymbol1 = QgsFillSymbol.createSimple({'color': '#00ff00ff'}) renderer.setSymbol(mySymbol1) layer.triggerRepaint() elif renderer and layer.geometryType() == 0 and min_val and max_val: print(layer.geometryType()) ranges = [] center = round((max_val - min_val) / 2, 0) range_1 = round((center - min_val) / 2, 0) range_2 = round(((max_val - center) / 2) + center, 0) print(min_val, range_1, center, range_2, max_val) symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(QColor("#0005ae")) myRange = QgsRendererRange(min_val - 0.001, range_1, symbol, str(round(min_val,2)) + " - " + str(range_1) + " (MWh/point)") ranges.append(myRange) symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(QColor("#fda000")) myRange = QgsRendererRange(range_1, range_2, symbol, str(range_1) + " - " + str(range_2) + " (MWh/point)") ranges.append(myRange) symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(QColor("#ff0000")) myRange = QgsRendererRange(range_2, max_val + 0.001, symbol, str(range_2) + " - " + str(round(max_val,2)) + " (MWh/point)") ranges.append(myRange) expression = attribute # field name renderer = QgsGraduatedSymbolRenderer(expression, ranges) layer.setRenderer(renderer) else: QMessageBox.information(None, "Error", "file " + file_name + " could not be loaded") if group_name is None: QgsProject.instance().addMapLayer(layer) else: QgsProject.instance().addMapLayer(layer, False) root = QgsProject.instance().layerTreeRoot() group = root.findGroup(group_name) if group is None: group = root.insertGroup(0, group_name) group.addLayer(layer) return layer
def __init__(self, iface, layer_name, svg_size, attributes, svg_resource, group=None, visible=True): "..." self.svg_path = os.path.dirname(__file__) + "/icons/" WGS84Layer.__init__(self, iface, layer_name, "Point", visible, group) symbol = QgsSymbol.defaultSymbol(self.layer.geometryType()) svgStyle = {} svgStyle['name'] = self.svg_path + svg_resource svgStyle['outline'] = '#00000' svgStyle['outline-width'] = '0' svgStyle['size'] = svg_size symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle) # Rotate the svg to reflect the orientation of a landmark # admap uses a counter-clockwise orientation with radians, qgis a clockwise and degrees dataDefinedAngle = QgsProperty.fromExpression('(-("Orientation" * 180 / pi()) - 90) % 360', True) symbol_layer.setDataDefinedProperty(QgsSymbolLayer.PropertyAngle, dataDefinedAngle) # Make the SVG size scalable with the zoom level of the map # i.e. less zoom, smaller SVG dataDefinedSize = QgsProperty.fromExpression( 'CASE WHEN @map_scale < 500 THEN 1000 / @map_scale ELSE 2 END', True) symbol_layer.setDataDefinedProperty(QgsSymbolLayer.PropertySize, dataDefinedSize) if symbol_layer is not None: symbols = self.layer.renderer().symbols(QgsRenderContext()) sym = symbols[0] sym.changeSymbolLayer(0, symbol_layer) self.layer.triggerRepaint() WGS84Layer.refresh_legend(self) self.set_attributes(attributes)
def _make_vector_renderer(layer, class_field, class_map): category_map = {} colors = ['Blue', 'Red', 'Green', 'Yellow'] for i, class_item in enumerate(class_map.get_items()): name = class_item.name color = class_item.color if color is None: color = colors[i % len(colors)] category_map[name] = (color, name) categories = [] for name, (color, label) in category_map.items(): symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol_layer = QgsSimpleLineSymbolLayer() symbol_layer.setWidth(0.5) symbol.changeSymbolLayer(0, symbol_layer) symbol.setColor(QColor(color)) category = QgsRendererCategory(label, symbol, name) categories.append(category) renderer = QgsCategorizedSymbolRenderer(class_field, categories) return renderer
def categoryze_layer(self, layer, cat_field, size): """ :param layer: QgsVectorLayer to be categorized (QgsVectorLayer) :param cat_field: Field to categorize (string) :param size: Size of feature (integer) """ # get unique values fields = layer.fields() fni = fields.indexOf(cat_field) unique_values = layer.dataProvider().uniqueValues(fni) categories = [] color_values={'NEW':QColor(0, 255, 0), 'DUPLICATED':QColor(255, 0, 0), 'EXISTS':QColor(240, 150, 0)} for unique_value in unique_values: # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(layer.geometryType()) if type(symbol) in (QgsLineSymbol, ): symbol.setWidth(size) else: symbol.setSize(size) # configure a symbol layer # layer_style = {} # layer_style['color'] = '%d, %d, %d' % (randrange(0, 256), randrange(0, 256), randrange(0, 256)) # layer_style['color'] = '255,0,0' # layer_style['outline'] = '#000000' try: color = color_values.get(unique_value) symbol.setColor(color) except: color = QColor(randrange(0, 256), randrange(0, 256), randrange(0, 256)) symbol.setColor(color) # layer_style['horizontal_anchor_point'] = '6' # layer_style['offset_map_unit_scale'] = '6' # layer_style['outline_width'] = '6' # layer_style['outline_width_map_unit_scale'] = '6' # layer_style['size'] = '6' # layer_style['size_map_unit_scale'] = '6' # layer_style['vertical_anchor_point'] = '6' # symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) # print(f"Symbollaye --> {symbol_layer}") # # replace default symbol layer with the configured one # if symbol_layer is not None: # symbol.changeSymbolLayer(0, symbol_layer) # create renderer object category = QgsRendererCategory(unique_value, symbol, str(unique_value)) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRenderer(cat_field, categories) # assign the created renderer to the layer if renderer is not None: layer.setRenderer(renderer) layer.triggerRepaint() self.iface.layerTreeView().refreshLayerSymbology(layer.id())
def prepare_route_symbol(nb_route): colors = ['#1f78b4', '#ffff01', '#ff7f00', '#fb9a99', '#b2df8a', '#e31a1c'] p = nb_route % len(colors) my_symb = QgsSymbol.defaultSymbol(1) my_symb.setColor(QColor(colors[p])) my_symb.setWidth(1.2) return my_symb
def setStyleIcon(self, svg): #Dato il path di un'icona svg la setta come stile per le sole features selezionate nel layer dei beni vlayer = self.getLayerBeni() if len(vlayer.selectedFeatures()) == 1: svgStyle = { "name": svg, "outline": "#000000", "size": "15", } svgLayer = QgsSvgMarkerSymbolLayer.create(svgStyle) svgSymbol = QgsMarkerSymbol() svgSymbol.changeSymbolLayer(0, svgLayer) symbol = QgsSymbol.defaultSymbol(vlayer.geometryType()) symbol.setColor(QColor("Blue")) centroid = QgsCentroidFillSymbolLayer() centroid.setSubSymbol(svgSymbol) selectedSymbol = QgsFillSymbol() selectedSymbol.changeSymbolLayer(0, centroid) renderer = QgsRuleBasedRenderer(symbol) rule = QgsRuleBasedRenderer.Rule(selectedSymbol, label="Selected", filterExp="is_selected()") renderer.rootRule().appendChild(rule) vlayer.setRenderer(renderer) vlayer.triggerRepaint()
def simple_polygon_without_brush(layer, width='0.26', color=QColor('black')): """Simple style to apply a border line only to a polygon layer. :param layer: The layer to style. :type layer: QgsVectorLayer :param color: Color to use for the line. Default to black. :type color: QColor :param width: Width to use for the line. Default to '0.26'. :type width: str """ registry = QgsApplication.symbolLayerRegistry() line_metadata = registry.symbolLayerMetadata("SimpleLine") symbol = QgsSymbol.defaultSymbol(layer.geometryType()) # Line layer line_layer = line_metadata.createSymbolLayer({ 'width': width, 'color': color.name(), 'offset': '0', 'penstyle': 'solid', 'use_custom_dash': '0', 'joinstyle': 'bevel', 'capstyle': 'square' }) # Replace the default layer with our custom line symbol.deleteSymbolLayer(0) symbol.appendSymbolLayer(line_layer) renderer = QgsSingleSymbolRenderer(symbol) layer.setRenderer(renderer)
def set_style_mapzones(self): extras = f'"mapzones":""' body = self.create_body(extras=extras) # self.controller.log_info(f"SELECT gw_fct_getstylemapzones ({body})") json_return = self.controller.get_json('gw_fct_getstylemapzones', body) if not json_return: return False for mapzone in json_return['body']['data']['mapzones']: # self.controller.log_info(f"Mapzone: ({mapzone})") # Loop for each mapzone returned on json lyr = self.controller.get_layer_by_tablename(mapzone['layer']) categories = [] status = mapzone['status'] if status == 'Disable': pass if lyr: # Loop for each id returned on json for id in mapzone['values']: # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(lyr.geometryType()) symbol.setOpacity(float(mapzone['opacity'])) # Setting simp R = random.randint(0, 255) G = random.randint(0, 255) B = random.randint(0, 255) if status == 'Stylesheet': try: R = id['stylesheet']['color'][0] G = id['stylesheet']['color'][1] B = id['stylesheet']['color'][2] except TypeError: R = random.randint(0, 255) G = random.randint(0, 255) B = random.randint(0, 255) elif status == 'Random': R = random.randint(0, 255) G = random.randint(0, 255) B = random.randint(0, 255) # Setting sytle layer_style = {'color': '{}, {}, {}'.format(int(R), int(G), int(B))} symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) category = QgsRendererCategory(id['id'], symbol, str(id['id'])) categories.append(category) # apply symbol to layer renderer lyr.setRenderer(QgsCategorizedSymbolRenderer(mapzone['idname'], categories)) # repaint layer lyr.triggerRepaint()
def styleMap(self): categories = [] for cat in range(0, self.districts + 1): symbol = QgsSymbol.defaultSymbol(self.activeLayer.geometryType()) layer_style = {} layer_style['color'] = '%d, %d, %d' % (randrange( 0, 256), randrange(0, 256), randrange(0, 256)) layer_style['outline'] = '#000000' symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) # create renderer object if cat == 0: category = QgsRendererCategory("", symbol, "") else: category = QgsRendererCategory(districtName[cat], symbol, str(districtName[cat])) # entry for the list of category items categories.append(category) renderer = QgsCategorizedSymbolRenderer(self.distfield, categories) # assign the created renderer to the layer if renderer is not None: self.activeLayer.setRenderer(renderer) self.activeLayer.triggerRepaint()
def create_elimlyr(canvas): elim_lyr = QgsVectorLayer(r"LineString?crs=epsg:4326&index=yes", elimedge_lname, r"memory") p_elimedge = elim_lyr.dataProvider() QgsProject.instance().addMapLayer(elim_lyr, True) # Case of only one color (elimedge_mono set in global_vars) if elimedge_mono: rend_symb=QgsSymbol.defaultSymbol(elim_lyr.geometryType()) rend_symb.setWidth(elimedge_wdt) rend_symb.setColor(QColor(elimedge_col)) rend_symb.setOpacity(elimedge_opc) rend_elimedge = QgsSingleSymbolRenderer(rend_symb) # Case of multiple colors depending on the type of elimination else: rend_elimedge = QgsRuleBasedRenderer(QgsLineSymbol()) edge_root_rule = rend_elimedge.rootRule() edge_rules = ((inter_rfu, "\"pb_type\" = '" + inter_rfu + "'", elimedge_col, elimedge_wdt), (inter_new, "\"pb_type\" = '" + inter_new + "'", elimedge_col2, elimedge_wdt)) 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) rule.symbol().setOpacity(elimedge_opc) edge_root_rule.appendChild(rule) edge_root_rule.removeChildAt(0) elim_lyr.setRenderer(rend_elimedge) p_elimedge.addAttributes(elimlyr_atts) elim_lyr.updateFields() # Refresh the canvas elim_lyr.triggerRepaint() return elim_lyr
def setupBackgroundLayer(self, stateLayer): ''' Sets symbol rules for background layer in localization component ''' symbol = QgsSymbol.defaultSymbol(stateLayer.geometryType()) registry = QgsSymbolLayerRegistry() fillMeta = registry.symbolLayerMetadata("SimpleFill") fillSymbolLayer = fillMeta.createSymbolLayer({ 'color': '201,201,201', 'outline_width': 0.1 }) # Replace the default style symbol.deleteSymbolLayer(0) symbol.appendSymbolLayer(fillSymbolLayer) renderer = QgsRuleBasedRenderer(symbol) rootRule = renderer.rootRule() for state in self.estados: # Appends the rule to the rootRule rule = self.createStateRule(rootRule, state) rootRule.appendChild(rule) # Delete the default rule rootRule.removeChildAt(0) # Apply the renderer to the layer stateLayer.setRenderer(renderer) stateLayer.triggerRepaint()
def setRenderer(layer): from qgis.core import QgsSymbol, QgsRendererCategory, QgsCategorizedSymbolRenderer, QgsMarkerSymbol from PyQt5.QtGui import QColor waste_level = { '0': ('green', 'clean'), '1': ('orange', 'medium'), '2': ('red', 'high'), '': ('grey', 'unknown') } # Symbols default_station = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'green', 'size':'5'}) clean_station = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'lightgreen', 'size':'4'}) medium_station = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'orange', 'size':'6'}) dirty_station = QgsMarkerSymbol.createSimple({'name': 'circle', 'color': 'red', 'size':'9'}) symbols = {'0': clean_station, '1': medium_station,'2': dirty_station,'': default_station} categories = [] for wastelevel, (color, label) in waste_level.items(): symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategory(wastelevel, symbols[wastelevel], label) categories.append(category) expression = 'wastelevel' # field name renderer = QgsCategorizedSymbolRenderer(expression, categories) layer.setRenderer(renderer) return True
def colorChange(self, layer, updated_attribute_table=False): # layer = iface.acitiveLayer() # load the layer as you want # define the lookup >> value : (color, label) if (updated_attribute_table): self.updated_attribute_table(layer) colors = { 1: ('red', 'Won'), 0: ('light grey', 'Lost'), -1: ('white', 'Undecided') } # create a category for each item in your layer categories = [] for unique_id, (color, label) in colors.items(): symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategory(unique_id, symbol, label) categories.append(category) # create the renderer and assign it to the layer expression = self.attrName renderer = QgsCategorizedSymbolRenderer(expression, categories) # for cat in renderer.categories(): # print("{}: {} :: {}".format(cat.value(), cat.label(), cat.symbol())) renderer = QgsCategorizedSymbolRenderer(expression, categories) layer.setRenderer(renderer) layer.triggerRepaint()
def set_rule_based_layer_style(layer: QgsVectorLayer, rules: List['StyleRule']) -> None: """Sets the rule based layer style.""" # Create a new rule-based renderer. symbol = QgsSymbol.defaultSymbol(layer.geometryType()) renderer = QgsRuleBasedRenderer(symbol) # Get the "root" rule. root_rule = renderer.rootRule() for r in rules: # Create a clone (i.e. a copy) of the default rule. rule = root_rule.children()[0].clone() # Set the label, expression and color. rule.setLabel(r.label) rule.setFilterExpression(r.expression) rule.symbol().setColor(QColor(r.color_name)) rule.symbol().setOpacity(r.opacity) # Set the scale limits if they have been specified. if r.scale_min_denom is not None and r.scale_max_denom is not None: rule.setScaleMinDenom(r.scale_min_denom) rule.setScaleMaxDenom(r.scale_max_denom) # Append the rule to the list of rules. root_rule.appendChild(rule) # Delete the default rule. root_rule.removeChildAt(0) # Apply the renderer to the layer. layer.setRenderer(renderer)
def create_rotation_item(self, map_point: QgsPointXY): f = self.create_feature(point=self.initial_point, rotation=0) # find symbol for feature renderer = self.current_layer().renderer().clone() context = QgsRenderContext.fromMapSettings(self.canvas().mapSettings()) context.expressionContext().appendScope( QgsExpressionContextUtils.layerScope(self.current_layer())) context.expressionContext().setFeature(f) renderer.startRender(context, self.current_layer().fields()) symbol = renderer.originalSymbolForFeature(f, context) if symbol is None: # e.g. code which doesn't match existing category if len(renderer.symbols(context)): symbol = renderer.symbols(context)[0] else: symbol = QgsSymbol.defaultSymbol( self.current_layer().geometryType()) renderer.stopRender(context) # clear existing data defined rotation symbol.setDataDefinedAngle(QgsProperty()) # render symbol to image symbol_image = GuiUtils.big_marker_preview_image( symbol, context.expressionContext()) self.rotation_item = PointRotationItem(self.canvas()) self.rotation_item.set_symbol(symbol_image) self.rotation_item.set_point_location(map_point) self.rotation_item.set_symbol_rotation(0) self.rotation_item.update()
def customRender(self, capa): if self.params.colorContorn is None: self.params.colorContorn = self.params.colorBase total = self.params.numCategories alpha = mv.MAP_ALPHA_INI maxAlpha = (255 - mv.MAP_ALPHA_FIN) step = round((maxAlpha - alpha) / (total - 1)) color = QColor(self.params.colorBase) decimals = self.params.maxDecimals(self.params.rangsCategories) categories = [] for i, r in enumerate(self.params.rangsCategories): color.setAlpha(alpha) alpha = min(alpha + step, maxAlpha) if self.params.simbol is None: symbol = QgsSymbol.defaultSymbol(capa.geometryType()) else: symbol = self.params.simbol.clone() self.setStrokeSymbology(symbol, self.params.colorContorn) symbol.setColor(color) f0 = self.params.numRang(r[0]) f1 = self.params.numRang(r[1]) label = QvApp().locale.toString(f0, 'f', decimals) + ' - ' + \ QvApp().locale.toString(f1, 'f', decimals) category = QgsRendererRange(f0, f1, symbol, label) categories.append(category) renderer = QgsGraduatedSymbolRenderer(self.params.campCalculat, categories) renderer.setMode(QgsGraduatedSymbolRenderer.Custom) # renderer.setClassAttribute(str(decimals)) capa.setRenderer(renderer) capa.setMapTipTemplate(self.params.calcTip()) capa.triggerRepaint() return renderer
def simple_polygon_without_brush(layer, width='0.26', color=QColor('black')): """Simple style to apply a border line only to a polygon layer. :param layer: The layer to style. :type layer: QgsVectorLayer :param color: Color to use for the line. Default to black. :type color: QColor :param width: Width to use for the line. Default to '0.26'. :type width: str """ registry = QgsApplication.symbolLayerRegistry() line_metadata = registry.symbolLayerMetadata("SimpleLine") symbol = QgsSymbol.defaultSymbol(layer.geometryType()) # Line layer line_layer = line_metadata.createSymbolLayer( { 'width': width, 'color': color.name(), 'offset': '0', 'penstyle': 'solid', 'use_custom_dash': '0', 'joinstyle': 'bevel', 'capstyle': 'square' }) # Replace the default layer with our custom line symbol.deleteSymbolLayer(0) symbol.appendSymbolLayer(line_layer) renderer = QgsSingleSymbolRenderer(symbol) layer.setRenderer(renderer)
def _set_line_colors(self, shapes_layer): layer_routes = QgsProject.instance().mapLayersByName('routes')[0] # join lineField = 'shape_id_short' routesField = 'route_id' joinObject = QgsVectorLayerJoinInfo() joinObject.setJoinFieldName(routesField) joinObject.setTargetFieldName(lineField) joinObject.setJoinLayerId(layer_routes.id()) joinObject.setUsingMemoryCache(True) joinObject.setJoinLayer(layer_routes) shapes_layer.addJoin(joinObject) # coloring target_field = 'routes_fid' features_shape = shapes_layer.getFeatures() myCategoryList = [] colors = {} for f in features_shape: r_fid = f['routes_fid'] if r_fid not in colors: colors[r_fid] = (f['routes_route_color'], f['routes_route_short_name']) for r_fid, r_item in colors.items(): symbol = QgsSymbol.defaultSymbol(shapes_layer.geometryType()) symbol.setColor(QColor('#' + r_item[0])) myCategory = QgsRendererCategory(r_fid, symbol, r_item[1]) myCategoryList.append(myCategory) myRenderer = QgsCategorizedSymbolRenderer(target_field, myCategoryList) shapes_layer.setRenderer(myRenderer) shapes_layer.triggerRepaint() self.gtfs.setProgress(95)
def createLayer(self): """create and add huntplugin layer to the layer tree""" if (self.alkisSelectAreaLayer is not None): parent = QgsProject.instance().layerTreeRoot().findLayer( self.alkisSelectAreaLayer).parent() layeropts = QgsVectorLayer.LayerOptions(False, False) self.init( ) # reinit main instances because alkis instance conninfo might have changed (db, conninfo) = self.core.openDB() if db is None: return self.huntSelectAreaLayer = QgsVectorLayer( u"%s estimatedmetadata=true checkPrimaryKeyUnicity=0 key='ogc_fid' type=MULTIPOLYGON srid=%d table=%s.po_polygons (polygon) sql=false" % (conninfo, self.alkisplugin.epsg, self.alkisplugin.quotedschema()), u"Jagd-Flächenmarkierung", "postgres", layeropts) sym = QgsSymbol.defaultSymbol(QgsWkbTypes.PolygonGeometry) sym.setColor(Qt.blue) sym.setOpacity(0.3) self.huntSelectAreaLayer.setRenderer(QgsSingleSymbolRenderer(sym)) QgsProject.instance().addMapLayer(self.huntSelectAreaLayer, False) parent.insertLayer(0, self.huntSelectAreaLayer) self.core.hlayer = None QgsProject.instance().writeEntry("hunt", "/areaMarkerLayer", self.huntSelectAreaLayer.id())
def stylePoly(self, layer): """ Style isochrone polygon layer. :param layer: Polygon layer to be styled. :type layer: QgsMapLayer """ if self.dimension == 'time': legend_suffix = ' mins' else: legend_suffix = ' m' field = layer.fields().lookupField(self.field_dimension_name) unique_values = sorted(layer.uniqueValues(field)) colors = { 0: QColor('#2b83ba'), 1: QColor('#64abb0'), 2: QColor('#9dd3a7'), 3: QColor('#c7e9ad'), 4: QColor('#edf8b9'), 5: QColor('#ffedaa'), 6: QColor('#fec980'), 7: QColor('#f99e59'), 8: QColor('#e85b3a'), 9: QColor('#d7191c') } categories = [] for cid, unique_value in enumerate(unique_values): # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(layer.geometryType()) # configure a symbol layer symbol_layer = QgsSimpleFillSymbolLayer( color=colors[cid], strokeColor=QColor('#000000')) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) # create renderer object category = QgsRendererCategory(unique_value, symbol, str(unique_value) + legend_suffix) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRenderer(self.field_dimension_name, categories) # assign the created renderer to the layer if renderer is not None: layer.setRenderer(renderer) layer.setOpacity(0.5) layer.triggerRepaint()
def hazard_class_style(layer, classification, display_null=False): """Set colors to the layer according to the hazard. :param layer: The layer to style. :type layer: QgsVectorLayer :param display_null: If we should display the null hazard zone. Default to False. :type display_null: bool :param classification: The hazard classification to use. :type classification: dict safe.definitions.hazard_classifications """ categories = [] # Conditional styling attribute_table_styles = [] for hazard_class, (color, label) in list(classification.items()): if hazard_class == not_exposed_class['key'] and not display_null: # We don't want to display the null value (not exposed). # We skip it. continue symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(color) if is_line_layer(layer): symbol.setWidth(line_width_exposure) category = QgsRendererCategory(hazard_class, symbol, label) categories.append(category) style = QgsConditionalStyle() style.setName(hazard_class) style.setRule("hazard_class='%s'" % hazard_class) style.setBackgroundColor(transparent) symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) symbol.setColor(color) symbol.setSize(3) style.setSymbol(symbol) attribute_table_styles.append(style) layer.conditionalStyles().setFieldStyles('hazard_class', attribute_table_styles) renderer = QgsCategorizedSymbolRenderer(hazard_class_field['field_name'], categories) layer.setRenderer(renderer)
def hazard_class_style(layer, classification, display_null=False): """Set colors to the layer according to the hazard. :param layer: The layer to style. :type layer: QgsVectorLayer :param display_null: If we should display the null hazard zone. Default to False. :type display_null: bool :param classification: The hazard classification to use. :type classification: dict safe.definitions.hazard_classifications """ categories = [] # Conditional styling attribute_table_styles = [] for hazard_class, (color, label) in list(classification.items()): if hazard_class == not_exposed_class['key'] and not display_null: # We don't want to display the null value (not exposed). # We skip it. continue symbol = QgsSymbol.defaultSymbol(layer.geometryType()) symbol.setColor(color) if is_line_layer(layer): symbol.setWidth(line_width_exposure) category = QgsRendererCategory(hazard_class, symbol, label) categories.append(category) style = QgsConditionalStyle() style.setName(hazard_class) style.setRule("hazard_class='%s'" % hazard_class) style.setBackgroundColor(transparent) symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) symbol.setColor(color) symbol.setSize(3) style.setSymbol(symbol) attribute_table_styles.append(style) layer.conditionalStyles().setFieldStyles( 'hazard_class', attribute_table_styles) renderer = QgsCategorizedSymbolRenderer( hazard_class_field['field_name'], categories) layer.setRenderer(renderer)
def testDefaultSymbol(self): p = QgsProjectStyleSettings() self.assertFalse(p.defaultSymbol(Qgis.SymbolType.Marker)) self.assertFalse(p.defaultSymbol(Qgis.SymbolType.Line)) self.assertFalse(p.defaultSymbol(Qgis.SymbolType.Fill)) marker = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) p.setDefaultSymbol(Qgis.SymbolType.Marker, marker) self.assertTrue(p.defaultSymbol(Qgis.SymbolType.Marker)) line = QgsSymbol.defaultSymbol(QgsWkbTypes.LineGeometry) p.setDefaultSymbol(Qgis.SymbolType.Line, line) self.assertTrue(p.defaultSymbol(Qgis.SymbolType.Line)) fill = QgsSymbol.defaultSymbol(QgsWkbTypes.PolygonGeometry) p.setDefaultSymbol(Qgis.SymbolType.Fill, fill) self.assertTrue(p.defaultSymbol(Qgis.SymbolType.Fill))
def _apply_symbology_fixed_divisions(self, layer, field, tbl_name, schema, min_v, max_v, steps): """Finds the amount of levels that is necessary to describe the layer, a maximum of 20 different levels is set. Parameters ---------- layer: QgsVectorLayer field: str tbl_name: str schema: str min_v: float max_v: float steps: int """ if min_v is not None and max_v is not None: distinct_values = list(np.arange(min_v, max_v, steps)) else: distinct = self.db.get_distinct(tbl_name, field, schema) if len(distinct) == 1: return distinct_values = [] distinct_count = [] for value, count in distinct: distinct_values.append(value) distinct_count.append(count) if len(distinct_values) > 20: distinct_values.sort() temp_list = [] for val in range(0, len(distinct_values), int(np.floor(len(distinct_values)/20))): temp_list.append(distinct_values[val]) if temp_list[-1] != distinct_values[-1]: temp_list.append(distinct_values[-1]) distinct_values = temp_list colors = self._create_colors(len(distinct_values)) # TODO: fix for str values! if len(distinct_values) > 19: range_list = [] for i in range(len(distinct_values) - 1): red, green, blue = colors[i] range_list.append(self._make_symbology(layer, distinct_values[i], distinct_values[i + 1], str(distinct_values[i]) + ' - ' + str(distinct_values[i + 1]), QColor(int(red*255),int(green*255), int(blue*255), 128) ) ) renderer = QgsGraduatedSymbolRenderer(field, range_list) renderer.setMode(QgsGraduatedSymbolRenderer.Custom ) else: categories = [] for i in range(len(distinct_values)): symbol = QgsSymbol.defaultSymbol(layer.geometryType()) red, green, blue = colors[i] symbol.setColor(QColor(int(red*255),int(green*255), int(blue*255), 128)) symbol.symbolLayer(0).setStrokeColor(QColor(int(red*255),int(green*255), int(blue*255), 128)) category = QgsRendererCategory(str(distinct_values[i]), symbol, str(distinct_values[i])) categories.append(category) renderer = QgsCategorizedSymbolRenderer(field, categories) #renderer.setMode(QgsCategorizedSymbolRenderer.Custom) layer.setRenderer(renderer)
def __init__(self, iface, layer_name, symbol, color, size, attributes, group=None, visible=True): "..." WGS84Layer.__init__(self, iface, layer_name, "Point", visible, group) props = self.layer.renderer().symbol().symbolLayer(0).properties() symbol = QgsSymbol.defaultSymbol(QgsWkbTypes.PointGeometry) symbol.setSize(1.5) self.layer.renderer().setSymbol(symbol) WGS84Layer.refresh_legend(self) self.set_attributes(attributes)
def create_simple_fill_symbol_layer(self, layer: QgsVectorLayer, fill_color: QColor): # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(layer.geometryType()) # configure a symbol layer symbol_layer = QgsSimpleFillSymbolLayer(fill_color) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) return symbol
def get_default_symbol( geom_type): symbol = QgsSymbol.defaultSymbol(geom_type) if symbol is None: if geom_type == Qgis.Point: symbol = QgsMarkerSymbol() elif geom_type == Qgis.Line: symbol = QgsLineSymbol() elif geom_type == Qgis.Polygon: symbol = QgsFillSymbol() return symbol
def setSectorsStyle(self, layer): # get unique values field = 'Class' fni = layer.fields().indexFromName(field) if fni == -1: # Hydraulic sectors field = 'SubNet' fni = layer.fields().indexFromName(field) unique_values = layer.dataProvider().uniqueValues(fni) # define categories categories = [] for unique_value in unique_values: # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(layer.geometryType()) # configure a symbol layer symbol_layer = None if layer.geometryType() == 0: # Point layer_style = dict() layer_style['color'] = '%d, %d, %d' % (randrange( 0, 256), randrange(0, 256), randrange(0, 256)) layer_style['size'] = str(2) symbol_layer = QgsSimpleMarkerSymbolLayer.create(layer_style) else: symbol = QgsLineSymbol().createSimple({}) symbol.deleteSymbolLayer(0) # Line lineSymbol = QgsSimpleLineSymbolLayer() lineSymbol.setWidthUnit(2) # Pixels lineSymbol.setWidth(1.5) lineSymbol.setColor( QColor(randrange(0, 256), randrange(0, 256), randrange(0, 256))) symbol.appendSymbolLayer(lineSymbol) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) # create renderer object category = QgsRendererCategory(unique_value, symbol, str(unique_value)) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRenderer(field, categories) # assign the created renderer to the layer if renderer is not None: layer.setRenderer(renderer)
def set_category_renderer(layer: QgsVectorLayer, column: str, start_color: Tuple[int, int, int], end_color: Tuple[int, int, int], unit: str = ''): ''' apply a category renderer to a layer. The categories will be the unique values of the given column with interpolated colors between given start and end color Parameters ---------- layer : QgsVectorLayer layer to apply the renderer to column : str name of the column containing the categories start_color : tuple rgb values of the first color in the color range end_color : tuple rgb values of the last color in the color range unit : str a unit to be added to the category label, defaults to no unit ''' idx = layer.fields().indexOf(column) unique_values = list(layer.uniqueValues(idx)) unique_values.sort() categories = [] geometry_type = layer.geometryType() for i, value in enumerate(unique_values): # initialize the default symbol for this geometry type symbol = QgsSymbol.defaultSymbol(geometry_type) # configure a symbol layer layer_style = {} rgb = [] for c in range(3): rgb.append(str(int(interpolate(start_color[c], end_color[c], i, len(unique_values))))) layer_style['color'] = ','.join(rgb) #layer_style['outline'] = '#000000' symbol_layer = QgsSimpleFillSymbolLayer.create(layer_style) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) # create renderer object category = QgsRendererCategory(value, symbol, f'{value} {unit}') # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRenderer(column, categories) layer.setRenderer(renderer)
def run(self): """Run method that performs all the real work""" layers = self.iface.mapCanvas().layers() layer_list = [] self.dlg.layerComboBox.clear() for layer in layers: layer_list.append(layer.name()) self.dlg.layerComboBox.addItems(layer_list) # TODO: Make the active layer the selected item in combo box aLayer = qgis.utils.iface.activeLayer() # TODO: Add signal to update toleranceSpinBox.suffix (Degrees) from layerComboBox.crs.mapUnits when layer is selected: #my_UnitType = { 0: 'Meters', 1: 'Feet', 2: 'Degrees', 7: 'NauticalMiles', 8: 'Kilometers', 9: 'Yards', 10: 'Miles', 3: 'UnknownUnit'} #suffix = my_UnitType[aLayer.crs().mapUnits()] # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: if self.checkNetworkXModule() < 0: return -4 import networkx as nx layerName = self.dlg.layerComboBox.currentText() try: aLayer = QgsProject.instance().mapLayersByName(layerName)[0] except: self.iface.messageBar().pushMessage("Error", "Failed to load layer!", level=Qgis.Critical) return -1 try: previousEditingMode = True if not aLayer.isEditable(): aLayer.startEditing() #self.iface.messageBar().pushMessage("Info", "Layer " + aLayer.name() + " needs to be in edit mode", level=Qgis.Info) #self.iface.messageBar().pushMessage("Error", "Layer " + aLayer.name() + " needs to be in edit mode", level=Qgis.Critical) #return -2 previousEditingMode = False attrIdx = self.getAttributeIndex(aLayer) if attrIdx < 0: return -3 progressMessageBar = self.iface.messageBar().createMessage("Creating network graph...") progress = QProgressBar() progress.setMaximum(aLayer.featureCount()) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, Qgis.Info) G = nx.Graph() aLayer.beginEditCommand("Clear group attribute, create graph") # construct undirected graph tolerance = self.dlg.toleranceSpinBox.value() if tolerance == 0: tolerance = 0.000001 count = 0 for feat in aLayer.getFeatures(): count += 1 progress.setValue(count) done = aLayer.changeAttributeValue(feat.id(), attrIdx, -1) geom = feat.geometry() QgsGeometry.convertToSingleType(geom) # QGIS 3.x seems to load single LineString as MultiLineString?? line = geom.asPolyline() for i in range(len(line)-1): G.add_edges_from([((int(line[i][0]/tolerance), int(line[i][1]/tolerance)), (int(line[i+1][0]/tolerance), int(line[i+1][1]/tolerance)), {'fid': feat.id()})]) # first scale by tolerance, then convert to int. Before doing this, there were problems (in NetworkX v1) with floats not equating, thus creating disconnects that weren't there. if count % 100 == 0: QApplication.processEvents() # keep the UI responsive, every 100 features #TODO: check to see if Esc pressed aLayer.endEditCommand() self.iface.messageBar().pushMessage("Finding connected subgraphs, please wait...", level=Qgis.Warning) # WARNING - to highlight the next stage, where we cannot show progress QApplication.processEvents() connected_components = list(nx.connected_component_subgraphs(G)) # this takes a long time. TODO: how to show progress? self.iface.messageBar().pushMessage("Updating group attribute...", level=Qgis.Info) QApplication.processEvents() # gather edges and components to which they belong fid_comp = {} for i, graph in enumerate(connected_components): for edge in graph.edges(data=True): fid_comp[edge[2].get('fid', None)] = i # write output to csv file #with open('C:/Tmp/Components.csv', 'wb') as f: # w = csv.DictWriter(f, fieldnames=['fid', 'group']) # w.writeheader() # for (fid, group) in fid_comp.items(): # w.writerow({'fid': fid, 'group': group}) aLayer.beginEditCommand("Update group attribute") for (fid, group) in fid_comp.items(): done = aLayer.changeAttributeValue(fid, attrIdx, group) aLayer.endEditCommand() groups = list(set(fid_comp.values())) if self.dlg.stylingCheckBox.isChecked(): aLayer.beginEditCommand("Update layer styling") categories = [] firstCat = True for cat in groups: symbol = QgsSymbol.defaultSymbol(aLayer.geometryType()) symbol.setColor(QColor(randint(0,255), randint(0,255), randint(0,255))) if firstCat: firstCat = False else: symbol.setWidth(symbol.width()*5) category = QgsRendererCategory(cat, symbol, "%d" % cat) categories.append(category) field = self.dlg.attributeNameEditBox.text() renderer = QgsCategorizedSymbolRenderer(field, categories) aLayer.setRenderer(renderer) # if self.iface.mapCanvas().isCachingEnabled(): # aLayer.setCacheImage(None) # else: # self.iface.mapCanvas().refresh() aLayer.triggerRepaint() aLayer.endEditCommand() self.iface.messageBar().clearWidgets() self.iface.messageBar().pushMessage("Found main network and %d disconnected islands in layer %s" % (len(groups)-1, aLayer.name()), level=Qgis.Success) aLayer.commitChanges() # if not previousEditingMode: except Exception as e: self.iface.messageBar().pushMessage("Error", "Exception caught: %s. Please report an issue to the author of the plugin." % repr(e), level=Qgis.Critical)