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 = QgsSymbolLayerV2Registry.instance() line_metadata = registry.symbolLayerMetadata("SimpleLine") symbol = QgsSymbolV2.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 = QgsSingleSymbolRendererV2(symbol) layer.setRendererV2(renderer)
def style_curves(self): registry = QgsSymbolLayerV2Registry.instance() cross = registry.symbolLayerMetadata("SimpleMarker").createSymbolLayer( { 'name': 'cross2', 'color': '0,0,0', 'color_border': '0,0,0', 'offset': '0,0', 'size': '1.5', 'angle': '0' }) symbol = QgsSymbolV2.defaultSymbol(self.layer.geometryType()) symbol.deleteSymbolLayer(0) symbol.appendSymbolLayer(cross) self._set_symbol_size(symbol) renderer = QgsSingleSymbolRendererV2(symbol) effect = QgsOuterGlowEffect() effect.setSpread(0.5) effect.setTransparency(0) effect.setColor(QColor(255, 255, 255)) effect.setBlurLevel(1) renderer.paintEffect().appendEffect(effect) renderer.paintEffect().setEnabled(True) self.layer.setRendererV2(renderer) self.layer.setLayerTransparency(30) # percent self.layer.triggerRepaint() self.iface.legendInterface().refreshLayerSymbology(self.layer) self.iface.mapCanvas().refresh()
def certificate_preprocess(plot, plots): """ Utility function that loads and renders plots that belong to a specific scheme. """ scheme_plot_layer = lht_plot_layer(plot.scheme_id, CERTIFICATE_PLOT) QgsMapLayerRegistry.instance().addMapLayer(scheme_plot_layer) # Get the EPSG code of the plot epsg_code = plot.cb_check_lht_plot_crs.value # Setting the project CRS variable QgsExpressionContextUtils.setProjectVariable('flts_source_crs', epsg_code) # Styling reference plot using primary key filter_exp = '"id" = ' + str(plot.id) scheme_symbol = QgsSymbolV2.defaultSymbol(scheme_plot_layer.geometryType()) # Rule-based rendering rule_renderer = QgsRuleBasedRendererV2(scheme_symbol) root_rule = rule_renderer.rootRule() # Rule for highlighting reference plot scheme_rule = root_rule.children()[0].clone() scheme_rule.setLabel('Reference Plot') scheme_rule.setFilterExpression(filter_exp) scheme_symbol_layer = scheme_rule.symbol().symbolLayer(0) scheme_symbol_layer.setFillColor(Qt.yellow) scheme_symbol_layer.setOutlineColor(Qt.black) scheme_symbol_layer.setBorderWidth(0.5) root_rule.appendChild(scheme_rule) # Rule for other plots def_rule = root_rule.children()[0].clone() def_rule.setLabel('Plots') def_rule.setIsElse(True) def_symbol_layer = def_rule.symbol().symbolLayer(0) def_symbol_layer.setFillColor(Qt.transparent) def_symbol_layer.setOutlineColor(Qt.black) root_rule.appendChild(def_rule) # Remove default rule root_rule.removeChildAt(0) # Set renderer scheme_plot_layer.setRendererV2(rule_renderer) # Enable labeling scheme_plot_layer.setCustomProperty("labeling", "pal") scheme_plot_layer.setCustomProperty("labeling/enabled", "true") scheme_plot_layer.setCustomProperty("labeling/fontFamily", "Arial") scheme_plot_layer.setCustomProperty("labeling/fontSize", "5.5") scheme_plot_layer.setCustomProperty("labeling/fieldName", "plot_number") scheme_plot_layer.setCustomProperty("labeling/placement", "1") scheme_plot_layer.setCustomProperty("labeling/centroidInside", "true") scheme_plot_layer.setCustomProperty("labeling/centroidWhole", "false") scheme_plot_layer.triggerRepaint() iface.mapCanvas().setExtent(scheme_plot_layer.extent()) QgsApplication.processEvents() return True
def style_categorized(self, layer, style_by): # get unique values fni = layer.fieldNameIndex(style_by) unique_values = layer.dataProvider().uniqueValues(fni) # define categories categories = [] for unique_value in unique_values: # initialize the default symbol for this geometry type symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) # configure a symbol layer layer_style = {} layer_style['color'] = '%d, %d, %d' % (randrange( 0, 256), randrange(0, 256), randrange(0, 256)) layer_style['outline'] = '#000000' symbol_layer = QgsSimpleFillSymbolLayerV2.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 = QgsRendererCategoryV2(unique_value, symbol, str(unique_value)) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRendererV2(style_by, categories) # assign the created renderer to the layer if renderer is not None: layer.setRendererV2(renderer) layer.triggerRepaint() self.iface.legendInterface().refreshLayerSymbology(layer) self.iface.mapCanvas().refresh()
def update_syms(self, catalogue): self.syms = {} for flag in set(catalogue.data['Cluster_Flag'].tolist()): for index in set(catalogue.data['Cluster_Index'].tolist()): # main shock point = QgsMarkerSymbolV2.createSimple( {'color': 'blue', 'name': 'square'}) if index: # belongs to a cluster color = self.catalogue_model.cluster_color(index) # non poissonian if flag: point = QgsMarkerSymbolV2.createSimple( {'color': 'blue', 'name': 'triangle'}) color.setAlpha(125 + 125 * abs(flag)) point.setSize(3) point.setColor(color) else: point = QgsSymbolV2.defaultSymbol(QGis.Point) point.setColor(QtGui.QColor("0,0,0,125")) point.setSize(1.5) self.syms[self.Cluster(index, flag)] = point
def setCategorizedStyle(vl, categories, field, **kwargs): """ set a categorized style """ # make a symbol for each category categoryV2List = [] for label, value, attrs in categories: symbolV2 = QgsSymbolV2.defaultSymbol( vl.geometryType() ) if 'color' in attrs: symbolV2.setColor( attrs['color'] ) if 'size' in attrs: symbolV2.setSize( attrs['size'] ) # in QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter if 'sizeScaleMethod' in kwargs and hasattr(symbolV2, 'setScaleMethod'): symbolV2.setScaleMethod( kwargs['sizeScaleMethod'] ) categoryV2 = QgsRendererCategoryV2( value, symbolV2, label ) categoryV2List.append( categoryV2 ) # create the renderer renderer = QgsCategorizedSymbolRendererV2( field, categoryV2List ) # set size scale field if 'sizeScaleField' in kwargs: renderer.setSizeScaleField( kwargs['sizeScaleField'] ) # set the renderer for the layer vl.setRendererV2( renderer ) Utils.iface.legendInterface().refreshLayerSymbology(vl)
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 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 = QgsSymbolLayerV2Registry.instance() line_metadata = registry.symbolLayerMetadata("SimpleLine") symbol = QgsSymbolV2.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 = QgsSingleSymbolRendererV2(symbol) layer.setRendererV2(renderer)
def setCategorizedStyle(vl, categories, field, **kwargs): """ set a categorized style """ # make a symbol for each category categoryV2List = [] for label, value, attrs in categories: symbolV2 = QgsSymbolV2.defaultSymbol(vl.geometryType()) if 'color' in attrs: symbolV2.setColor(attrs['color']) if 'size' in attrs: symbolV2.setSize(attrs['size']) # in QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter if 'sizeScaleMethod' in kwargs and hasattr(symbolV2, 'setScaleMethod'): symbolV2.setScaleMethod(kwargs['sizeScaleMethod']) categoryV2 = QgsRendererCategoryV2(value, symbolV2, label) categoryV2List.append(categoryV2) # create the renderer renderer = QgsCategorizedSymbolRendererV2(field, categoryV2List) # set size scale field if 'sizeScaleField' in kwargs: renderer.setSizeScaleField(kwargs['sizeScaleField']) # set the renderer for the layer vl.setRendererV2(renderer) Utils.iface.legendInterface().refreshLayerSymbology(vl)
def symbolize(self): # define ranges: label, lower value, upper value, color name temp_cat = (('0-10', 0.0, 10.0, '"#0024E3'), ('10-12', 10.0, 12.0, '#0087CD'), ('12-14', 12.0, 14.0, '#16F45A'), ('14-16', 14.0, 16.0, '#73FF1A'), ('16-18', 16.0, 18.0, '#BDFF0C'), ('18-20', 18.0, 20.0, '#FFDD00'), ('20-22', 20.0, 22.0, '#FF9000'), ('22-24', 22.0, 24.0, '#FF4400'), ('24-26', 24.0, 26.0, '#FF1D00'), ('26-28', 26.0, 28.0, 'F70000'), ('>28', 28.0, 40.0, '#AA0000')) # create a category for each item in Augmean ranges = [] for label, lower, upper, color in temp_cat: symbol = QgsSymbolV2.defaultSymbol(self.layer.geometryType()) symbol.setColor(QColor(color)) symbol.setWidth(0.5) rng = QgsRendererRangeV2(lower, upper, symbol, label) ranges.append(rng) # create the renderer and assign it to a layer expression = [] for feature in layer.getFeatures(): attrs = feature.attributes() sum(attrs[29:33]) / 6 self.renderer = QgsGraduatedSymbolRendererV2(expression, ranges)
def showLegend(self, layer, field, setting_list): if not self.cellstyle: self.styleManager = QgsMapLayerStyleManager(layer) self.styleManager.addStyleFromLayer(u'默认') self.cellstyle = True ranges = [] flabel = QLabel(field) fl = QHBoxLayout() fl.addWidget(flabel) self.vbox.addLayout(fl) for bl in setting_list: widget = QWidget(self) widget.setStyleSheet('QWidget {background-color:%s}' % bl[0].name()) widget.resize(20, 20) label = QLabel(str(bl[1]) + u'—' + str(bl[2])) c = QHBoxLayout() c.addWidget(widget) c.addWidget(label) c.setStretchFactor(widget, 1) c.setStretchFactor(label, 3) self.vbox.addLayout(c) sym = QgsSymbolV2.defaultSymbol(layer.geometryType()) sym.setColor(bl[0]) rng = QgsRendererRangeV2(bl[1], bl[2], sym, label.text()) ranges.append(rng) self.vbox.addStretch(1) self.setLayout(self.vbox) renderer = QgsGraduatedSymbolRendererV2(field, ranges) layer.setRendererV2(renderer) self.iface.actionDraw().trigger()
def run(self): """Specific stuff at tool activating.""" s = QSettings() layer = iface.mapCanvas().currentLayer() if not layer: return if findButtonByActionName("Afficher avancement de la saisie").isChecked(): # define a lookup: value -> (color, label) completion = {0: ("#ddd", "Aucune saisie"), 1: ("#7a7", "Saisie partielle"), 2: ("#0c0", "Saisie complète")} # create a category for each item categories = [] for completion_code, (color, label) in completion.items(): symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategoryV2(completion_code, symbol, label) categories.append(category) # create the renderer and assign it to a layer expression = "lgd_compl" # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) styleName = pluginDirectory + "/" + layer.name() + ".qml" if not s.value("layer_lgd_style/" + layer.name()): layer.saveNamedStyle(styleName) layer.setRendererV2(renderer) s.setValue("layer_lgd_style/" + layer.name(), 1) else: styleName = pluginDirectory + "/" + layer.name() + ".qml" layer.loadNamedStyle(styleName) s.setValue("layer_lgd_style/" + layer.name() + "/", 0) layer.triggerRepaint()
def prepare_route_symbol(nb_route): colors = ['#1f78b4', '#ffff01', '#ff7f00', '#fb9a99', '#b2df8a', '#e31a1c'] p = nb_route % len(colors) my_symb = QgsSymbolV2.defaultSymbol(1) my_symb.setColor(QColor(colors[p])) my_symb.setWidth(1.2) return my_symb
def create_join_renderer(self, layer, field, classes, mode, color='PuBu'): symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) style = QgsStyleV2().defaultStyle() colorRamp = style.colorRampRef(color) renderer = QgsGraduatedSymbolRendererV2.createRenderer(layer, field, classes, mode, symbol, colorRamp) label_format = self.create_join_label_format(2) renderer.setLabelFormat(label_format) return 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 classification.iteritems(): 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 = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(color) if is_line_layer(layer): symbol.setWidth(line_width_exposure) category = QgsRendererCategoryV2(hazard_class, symbol, label) categories.append(category) style = QgsConditionalStyle() style.setName(hazard_class) style.setRule("hazard_class='%s'" % hazard_class) style.setBackgroundColor(transparent) symbol = QgsSymbolV2.defaultSymbol(QGis.Point) symbol.setColor(color) symbol.setSize(3) style.setSymbol(symbol) attribute_table_styles.append(style) layer.conditionalStyles().setFieldStyles( 'hazard_class', attribute_table_styles) renderer = QgsCategorizedSymbolRendererV2( hazard_class_field['field_name'], categories) layer.setRendererV2(renderer)
def getSymbol(self): """docstring for __getSymbol""" symbol = QgsSymbolV2.defaultSymbol(self.qgslayer.geometryType()) new_symbol = self.__getQgsSymbol(symbol) if new_symbol: new_symbol.deleteSymbolLayer(0) return new_symbol return symbol
def apply(self, layer): symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol_layer = QgsSimpleFillSymbolLayerV2.create({'color': self.color}) if self.border_style: symbol_layer.setBorderStyle(self.border_style) self.renderer = QgsSingleSymbolRendererV2(symbol) self.renderer.symbols()[0].changeSymbolLayer(0, symbol_layer) super(SimpleFillSymbology, self).apply(layer)
def color_layers(self): """ Attempts to assign and color each layer after changing it's renderer to the Categorized Symbol Renderer TODO: Implement a store value to look up default names to get standardized Color Grading, If possible :return: None """ p = QgsMapLayerRegistry.instance().mapLayers() regex = re.compile("\n?(\D*)\d*\n?") for key, val in p.iteritems(): try: catagories = [] a = regex.match(key) fcn = QgsVectorGradientColorRampV2() # renderer.setWeightExpression(a.group(1)) # fcn.setColor1(QColor(255, 255, 255, 0)) # fcn.setColor2(QColor(random.randint(0, 100), random.randint( # 50, 255), random.randint(50, 255), 255)) fcn.setColor1(QColor(255, 0, 0, 255)) fcn.setColor2(QColor(0, 255, 0, 255)) # self.com.log(str(fcn.stops()), level=0) fcn.setStops([QgsGradientStop(0.5, QColor(255, 207, 74, 255))]) # renderer.setColorRamp(fcn) # renderer.setRenderQuality(1) # Max out the quality # for feature in val.getFeature(): # print feature.attribute(a.group(1)) fni = val.fieldNameIndex(a.group(1)) # This function is accomplishing the Classify Function, due to # the lack of API implementation sortedlist = [] for unique in val.dataProvider().uniqueValues(fni): sortedlist.append(unique) sortedlist.sort() for i in sortedlist: symbol = QgsSymbolV2.defaultSymbol(val.geometryType()) category = QgsRendererCategoryV2(i, symbol, str(i)) catagories.append(category) renderer = QgsCategorizedSymbolRendererV2( a.group(1), catagories) self.com.log(str(renderer.categories()), level=0) renderer.updateColorRamp(fcn) # renderer.updateCategoryValue(a.group(1)) val.setRendererV2(renderer) except AttributeError: # This will allow the Color step to continue if it hits an # Object it can't use (Raster layer) continue
def setStyleGrilleControle(layerGrille, idList): # Symbologie: cellule a controler props1 = {'color': '241,241,241,0', 'size': '0', 'color_border': '255,0,0'} symbol1 = QgsFillSymbolV2.createSimple(props1) #props2 = {'color': '255,127,0,0', 'size':'0', 'color_border' : '255,127,0', 'width_border':'1'} #symbol2 = QgsFillSymbolV2.createSimple(props2) # Symbologie: cellule a griser props3 = { 'color': '180,180,180', 'size': '1', 'color_border': '180,180,180' } symbol3 = QgsFillSymbolV2.createSimple(props3) symbol3.setAlpha(0.70) # On definit les règles de symbologie txtRule = ' in (' for i in range(len(idList)): id = idList[i] txtRule = txtRule + str(id) + ', ' txtRule = txtRule[0:len(txtRule) - 2] txtRule = txtRule + ')' cell_rules = (('A controler', CONST_ATTRIBUT_ID + ' ' + txtRule, symbol1), ('Pass', CONST_ATTRIBUT_ID + ' not ' + txtRule, symbol3)) # create a new rule-based renderer symbol = QgsSymbolV2.defaultSymbol(layerGrille.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) # get the "root" rule root_rule = renderer.rootRule() for label, expression, symbol in cell_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(label) rule.setFilterExpression(expression) # rule.symbol().setColor(QColor(color_name)) rule.setSymbol(symbol) # 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 layerGrille.setRendererV2(renderer) return layerGrille
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 classification.iteritems(): 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 = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(color) if is_line_layer(layer): symbol.setWidth(line_width_exposure) category = QgsRendererCategoryV2(hazard_class, symbol, label) categories.append(category) style = QgsConditionalStyle() style.setName(hazard_class) style.setRule("hazard_class='%s'" % hazard_class) symbol = QgsSymbolV2.defaultSymbol(QGis.Point) symbol.setColor(color) symbol.setSize(3) style.setSymbol(symbol) attribute_table_styles.append(style) layer.conditionalStyles().setFieldStyles( 'hazard_class', attribute_table_styles) renderer = QgsCategorizedSymbolRendererV2( hazard_class_field['field_name'], categories) layer.setRendererV2(renderer)
def create_join_renderer(layer, field, classes, mode, color='Blues'): symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) style = QgsStyleV2().defaultStyle() colorRamp = style.colorRampRef(color) renderer = QgsGraduatedSymbolRendererV2.createRenderer( layer, field, classes, mode, symbol, colorRamp) label_format = create_join_label_format(2) renderer.setLabelFormat(label_format) return renderer
def __init__(self): QgsFeatureRendererV2.__init__(self, "CatalogueCompletenessRenderer") complete = QgsSymbolV2.defaultSymbol(QGis.Point) uncomplete = QgsMarkerSymbolV2.createSimple( {'color': 'blue', 'name': 'triangle'}) uncomplete.setSize(3) complete.setSize(1.5) complete.setColor(QtGui.QColor(255, 0, 0, 125)) self.syms = [complete, uncomplete]
def applySymbology(self): self.getConnection() vlayer = qgis.utils.iface.mapCanvas().currentLayer() if vlayer == None: return fields = vlayer.dataProvider().fields() classField = None for f in fields: if f.name() == "classtype": classField = 'classtype' elif f.name() == "result": classField = 'result' print classField class_loaded = False for layer in QgsMapLayerRegistry.instance().mapLayers().values(): if layer.name() == "class": vlayerClass = layer class_loaded = True if not class_loaded: uriSubClass = QgsDataSourceURI() uriSubClass.setConnection(self.serverName, "5432", self.database, self.usr , self.pw) uriSubClass.setDataSource("classification", "class", None, "", "id") vlayerClass = QgsVectorLayer(uriSubClass.uri(), "class", "postgres") QgsMapLayerRegistry.instance().addMapLayer(vlayerClass) for field in fields: index = vlayer.fieldNameIndex(field.name()) if field.name() == classField: vlayer.editFormConfig().setWidgetType(index, 'ValueRelation') vlayer.editFormConfig().setWidgetConfig(index, {'Layer': vlayerClass.id(), 'Key': 'id', 'Value': 'classname'}) useJoin = True if useJoin: joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = vlayerClass.id() joinObject.joinFieldName = 'id' joinObject.targetFieldName = classField joinObject.memoryCache = True vlayer.addJoin(joinObject) self.join.append(joinObject) categories = [] iter = vlayerClass.getFeatures() for feature in iter: classname = feature['classname'] color = QColor(feature['red'], feature['green'], feature['blue']) sym = QgsSymbolV2.defaultSymbol(vlayer.geometryType()) sym.setColor(QColor(color)) category = QgsRendererCategoryV2(classname, sym, classname) categories.append(category) field = "class_classname" renderer = QgsCategorizedSymbolRendererV2(field, categories) vlayer.setRendererV2(renderer) qgis.utils.iface.messageBar().pushMessage("Information", "Editor widget set", level = qgis.gui.QgsMessageBar.INFO, duration = 5) qgis.utils.iface.setActiveLayer(vlayer)
def render_and_save_pointwise_output_layer( self, pointwise_output_csv_filepath, output_layer_name, on_values_of_attribute, graduated_rendering_interval_points, shapefile_path=''): uri = 'file:///' + pointwise_output_csv_filepath + \ '?delimiter=%s&crs=epsg:32643&xField=%s&yField=%s' % (',', 'X', 'Y') output_layer = QgsVectorLayer(uri, output_layer_name, 'delimitedtext') if 'Crop' in on_values_of_attribute: ET_D_max = max([ point.budget.PET_minus_AET_crop_end for point in model_calculator.output_grid_points ]) elif 'Monsoon' in on_values_of_attribute: ET_D_max = max([ point.budget.PET_minus_AET_monsoon_end for point in model_calculator.output_grid_points ]) graduated_symbol_renderer_range_list = [] opacity = 1 intervals_count = len(graduated_rendering_interval_points) for i in range(intervals_count): interval_min = 0 if graduated_rendering_interval_points[ i] == 0 else ( graduated_rendering_interval_points[i] * ET_D_max / 100.0 + 0.01) interval_max = (graduated_rendering_interval_points * ET_D_max / 100.0) label = "{0:.2f} - {1:.2f}".format(interval_min, interval_max) colour = QColor( int(255 * (1 - (i + 1.0) / (intervals_count + 1.0))), 0, 0) # +1 done to tackle boundary cases symbol = QgsSymbolV2.defaultSymbol(output_layer.geometryType()) symbol.setColor(colour) symbol.setAlpha(opacity) interval_range = QgsRendererRangeV2(interval_min, interval_max, symbol, label) graduated_symbol_renderer_range_list.append(interval_range) renderer = QgsGraduatedSymbolRendererV2( '', graduated_symbol_renderer_range_list) renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) renderer.setClassAttribute(on_values_of_attribute) output_layer.setRendererV2(renderer) QgsMapLayerRegistry.instance().addMapLayer(output_layer) if shapefile_path != '': QgsVectorFileWriter.writeAsVectorFormat(output_layer, shapefile_path, "utf-8", None, "ESRI Shapefile") return output_layer
def commitClicked(self): feature = self.listWidget.currentItem().feature geom = None self.attributesTable.setRowCount(len(feature)) for idx, attrname in enumerate(feature): value = feature[attrname] font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(attrname) item.setFont(font) self.attributesTable.setItem(idx, 0, item) self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value))) if geom is None: try: geom = QgsGeometry.fromWkt(value) except: pass self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True) settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') types = ["Point", "LineString", "Polygon"] layers = [] if geom is not None: geomtype = types[int(geom.type())] layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory") pr = layer.dataProvider() feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) layer.updateExtents() layer.selectAll() layer.setExtent(layer.boundingBoxOfSelected()) layer.invertSelection() symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(Qt.green) symbol.setAlpha(0.5) if QGis.QGIS_VERSION_INT < 29900: layer.setRendererV2(QgsSingleSymbolRendererV2(symbol)) else: layer.setRenderer(QgsSingleSymbolRenderer(symbol)) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)]) QgsMapLayerRegistry.instance().addMapLayer(layer, False) self.mapCanvas.setExtent(layer.extent()) self.mapCanvas.setRenderFlag(True) layers.append(layer) else: self.mapCanvas.setLayerSet([]) settings.setValue('/Projections/defaultBehaviour', prjSetting)
def test_setRendererV2(self): layer = createLayerWithOnePoint() self.rendererChanged = False layer.rendererChanged.connect(self.onRendererChanged) r = QgsSingleSymbolRendererV2(QgsSymbolV2.defaultSymbol(QGis.Point)) layer.setRendererV2(r) self.assertTrue(self.rendererChanged) self.assertEquals(layer.rendererV2(), r)
def validatedDefaultSymbol(geometryType): symbol = QgsSymbolV2.defaultSymbol(geometryType) if symbol is None: if geometryType == QGis.Point: symbol = QgsMarkerSymbolV2() elif geometryType == QGis.Line: symbol = QgsLineSymbolV2() elif geometryType == QGis.Polygon: symbol = QgsFillSymbolV2() return symbol
def get_default_symbol( geom_type): symbol = QgsSymbolV2.defaultSymbol(geom_type) if symbol is None: if geom_type == QGis.Point: symbol = QgsMarkerSymbolV2() elif geom_type == QGis.Line: symbol = QgsLineSymbolV2() elif geom_type == QGis.Polygon: symbol = QgsFillSymbolV2() return symbol
def commitClicked(self): feature = self.listWidget.currentItem().feature geom = None self.attributesTable.setRowCount(len(feature)) for idx, attrname in enumerate(feature): value = feature[attrname] font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(attrname) item.setFont(font) self.attributesTable.setItem(idx, 0, item); self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value))); if geom is None: try: geom = QgsGeometry.fromWkt(value) except: pass self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True) settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') types = ["Point", "LineString", "Polygon"] layers = [] if geom is not None: geomtype = types[int(geom.type())] layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory") pr = layer.dataProvider() feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) layer.updateExtents() layer.selectAll() layer.setExtent(layer.boundingBoxOfSelected()) layer.invertSelection() symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(Qt.green) symbol.setAlpha(0.5) if QGis.QGIS_VERSION_INT < 29900: layer.setRendererV2(QgsSingleSymbolRendererV2(symbol)) else: layer.setRenderer(QgsSingleSymbolRenderer(symbol)) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)]) QgsMapLayerRegistry.instance().addMapLayer(layer, False) self.mapCanvas.setExtent(layer.extent()) self.mapCanvas.setRenderFlag(True) layers.append(layer) else: self.mapCanvas.setLayerSet([]) settings.setValue('/Projections/defaultBehaviour', prjSetting)
def test_setRendererV2( self ): layer = createLayerWithOnePoint() self.rendererChanged = False QObject.connect( layer, SIGNAL( "rendererChanged()" ), self.onRendererChanged ) r = QgsSingleSymbolRendererV2( QgsSymbolV2.defaultSymbol( QGis.Point ) ) layer.setRendererV2( r ) assert self.rendererChanged == True assert layer.rendererV2() == r
def test_setRendererV2(self): layer = createLayerWithOnePoint() self.rendererChanged = False QObject.connect(layer, SIGNAL("rendererChanged()"), self.onRendererChanged) r = QgsSingleSymbolRendererV2(QgsSymbolV2.defaultSymbol(QGis.Point)) layer.setRendererV2(r) assert self.rendererChanged == True assert layer.rendererV2() == r
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""" 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) 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(round(len(distinct_values) / 20))): temp_list.append(distinct_values[val]) distinct_values = temp_list colors = self._create_colors(len(distinct_values)) try: 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 = QgsGraduatedSymbolRendererV2(field, range_list) renderer.setMode(QgsGraduatedSymbolRendererV2.Custom) except TypeError: categories = [] for i in range(len(distinct_values)): symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) red, green, blue = colors[i] symbol.setColor( QColor(int(red * 255), int(green * 255), int(blue * 255), 128)) symbol.symbolLayer(0).setOutlineColor( QColor(int(red * 255), int(green * 255), int(blue * 255), 128)) category = QgsRendererCategoryV2(str(distinct_values[i]), symbol, str(distinct_values[i])) categories.append(category) renderer = QgsCategorizedSymbolRendererV2(field, categories) #renderer.setMode(QgsCategorizedSymbolRendererV2.Custom) layer.setRendererV2(renderer)
def _validated_default_symbol(self, geometryType): """Validates that the symbol is of the correct type, (point, line or polygon and then returning a Qgis type symbol)""" symbol = QgsSymbolV2.defaultSymbol(geometryType) if symbol is None: if geometryType == QGis.Point: symbol = QgsMarkerSymbolV2() elif geometryType == QGis.Line: symbol = QgsLineSymbolV2() elif geometryType == QGis.Polygon: symbol = QgsFillSymbolV2() return symbol
def make_svg_node_sym_renderer(self, vlay, icon_name, size): current_dir = os.path.dirname(__file__) svg_style = dict() svg_style['name'] = os.path.join(current_dir, icon_name) svg_style['size'] = str(size) symbol_layer = QgsSvgMarkerSymbolLayerV2.create(svg_style) symbol = QgsSymbolV2.defaultSymbol(vlay.geometryType()) symbol.changeSymbolLayer(0, symbol_layer) renderer = QgsSingleSymbolRendererV2(symbol) return renderer
def apply(self, layer): ranges = [] for lower, upper, label, color in self.ranges: symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(color) if self.no_pen: #symbol.setColorBorder('255, 0, 0, 0') symbol.symbolLayer(0).setOutlineColor(QtGui.QColor(255, 0, 0, 0)) ranges.append(QgsRendererRangeV2(lower, upper, symbol, label)) self.renderer = QgsGraduatedSymbolRendererV2(self.field, ranges) #self.renderer.setClassAttribute(self.field) #self.renderer.setSourceColorRamp(self.color_ramp) #self.renderer.setInvertedColorRamp(self.inverted) #self.renderer.updateColorRamp(inverted=self.inverted) super(GraduatedSymbology, self).apply(layer)
def setStyleGrilleSaisie(layerGrille, currid): props1 = { 'color': '241,241,241,0', 'size': '0', 'color_border': '255,0,0', 'width_border': '0.5' } symbol1 = QgsFillSymbolV2.createSimple(props1) props2 = {'color': '255,127,0,0', 'size': '0', 'color_border': '255,127,0'} symbol2 = QgsFillSymbolV2.createSimple(props2) # On definit les règles de symbologie cell_rules = (('Cellule en cours', CONST_ATTRIBUT_ID + ' = ' + str(currid), symbol1), ('Autre cellule', CONST_ATTRIBUT_ID + ' != ' + str(currid), symbol2)) # create a new rule-based renderer symbol = QgsSymbolV2.defaultSymbol(layerGrille.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) # get the "root" rule root_rule = renderer.rootRule() for label, expression, symbol in cell_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(label) rule.setFilterExpression(expression) # rule.symbol().setColor(QColor(color_name)) rule.setSymbol(symbol) # 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 layerGrille.setRendererV2(renderer) return layerGrille
def vector_apply_unique_value_renderer(vector_layer, column): """Apply colours to each unique value for a vector layer column. source: https://gis.stackexchange.com/a/175114 Args: vector_layer (QgsVectorLayer): A vector layer to apply unique symbology to. column (str): The column containing the unique values """ categories = [] uniq_vals = vector_layer.dataProvider().uniqueValues( vector_layer.fieldNameIndex(column)) randcolors = random_colours(len(uniq_vals)) for i, ea_value in enumerate(uniq_vals): # initialize the default symbol for this geometry type symbol = QgsSymbolV2.defaultSymbol(vector_layer.geometryType()) # configure a symbol layer layer_style = { 'color': '{}, {}, {}'.format(*randcolors[i]), 'outline': '#000000' } symbol_layer = QgsSimpleFillSymbolLayerV2.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 = QgsRendererCategoryV2(ea_value, symbol, str(ea_value)) # entry for the list of category items categories.append(category) # create renderer object renderer = QgsCategorizedSymbolRendererV2(column, categories) # assign the created renderer to the layer if renderer is not None: vector_layer.setRendererV2(renderer) # refresh vector_layer.triggerRepaint()
def make_OD_markers(nb, xo, yo, xd, yd, list_coords=None): """ Prepare the Origin (green), Destination (red) and Intalternative_geometriesermediates (grey) markers. """ OD_layer = QgsVectorLayer( "Point?crs=epsg:4326&field=id_route:integer&field=role:string(80)", "markers_osrm{}".format(nb), "memory") features = [] fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(xo), float(yo)))) fet.setAttributes([nb, 'Origin']) features.append(fet) fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(xd), float(yd)))) fet.setAttributes([nb, 'Destination']) features.append(fet) marker_rules = [ ('Origin', '"role" LIKE \'Origin\'', '#50b56d', 4), ('Destination', '"role" LIKE \'Destination\'', '#d31115', 4), ] if list_coords: for i, pt in enumerate(list_coords): fet = QgsFeature() fet.setGeometry( QgsGeometry.fromPoint(QgsPoint(float(pt[0]), float(pt[1]))) ) fet.setAttributes([nb, 'Via point n°{}'.format(i)]) features.append(fet) marker_rules.insert( 1, ('Intermediate', '"role" LIKE \'Via point%\'', 'grey', 2)) OD_layer.dataProvider().addFeatures(features) symbol = QgsSymbolV2.defaultSymbol(OD_layer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() for label, expression, color_name, size in marker_rules: rule = root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QtGui.QColor(color_name)) rule.symbol().setSize(size) root_rule.appendChild(rule) root_rule.removeChildAt(0) OD_layer.setRendererV2(renderer) return OD_layer
def make_OD_markers(nb, xo, yo, xd, yd, list_coords=None): """ Prepare the Origin (green), Destination (red) and Intermediates (grey) markers. """ OD_layer = QgsVectorLayer( "Point?crs=epsg:4326&field=id_route:integer&field=role:string(80)", "markers_osrm{}".format(nb), "memory") features = [] fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(xo), float(yo)))) fet.setAttributes([nb, 'Origin']) features.append(fet) fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(xd), float(yd)))) fet.setAttributes([nb, 'Destination']) features.append(fet) marker_rules = [ ('Origin', '"role" LIKE \'Origin\'', '#50b56d', 4), ('Destination', '"role" LIKE \'Destination\'', '#d31115', 4), ] if list_coords: for i, pt in enumerate(list_coords): fet = QgsFeature() fet.setGeometry( QgsGeometry.fromPoint(QgsPoint(float(pt[0]), float(pt[1])))) fet.setAttributes([nb, 'Via point n°{}'.format(i)]) features.append(fet) marker_rules.insert( 1, ('Intermediate', '"role" LIKE \'Via point%\'', 'grey', 2)) OD_layer.dataProvider().addFeatures(features) symbol = QgsSymbolV2.defaultSymbol(OD_layer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() for label, expression, color_name, size in marker_rules: rule = root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QtGui.QColor(color_name)) rule.symbol().setSize(size) root_rule.appendChild(rule) root_rule.removeChildAt(0) OD_layer.setRendererV2(renderer) return OD_layer
def symbolize(layer, oldlayer): renderer = None # See if we can figure out ho thick the line is to begin with: # create a new single symbol renderer symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) renderer = QgsSingleSymbolRendererV2(symbol) # symbol_layer = QgsSimpleLineSymbolLayerV2.create(properties) symbol_layer = QgsSimpleLineSymbolLayerV2(random_color(), 2.0) # assign the symbol layer to the symbol # TODO: on windows::: 'NoneType' object has no attribute 'appendSymbolLayer' renderer.symbol().appendSymbolLayer(symbol_layer) # assign the renderer to the layer layer.setRendererV2(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.rendererV2().symbol().symbolLayer(0).properties() symbol = QgsSymbolV2.defaultSymbol(QGis.Point) symbol.setSize(1.5) self.layer.rendererV2().setSymbol(symbol) WGS84Layer.refresh_legend(self) self.set_attributes(attributes)
def make(cls, catalogue_map): layer = catalogue_map.catalogue_layer symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) ramp = QgsVectorGradientColorRampV2.create( dict(color1='white', color2='blue')) symbol.setSize(0.15) # number of color classes = 8 renderer = cls.createRenderer( layer, "depth", 8, QgsGraduatedSymbolRendererV2.Quantile, symbol, ramp) renderer.setSizeScaleField("_magnitude") renderer.setScaleMethod(QgsSymbolV2.ScaleDiameter) renderer.update_syms = lambda x: x return renderer
def add_final_pts(self, pts): center_pt_layer = QgsVectorLayer( "Point?crs=epsg:4326&field=id_center:integer&field=role:string(80)", "center_{}".format(self.nb_isocr), "memory") my_symb = QgsSymbolV2.defaultSymbol(0) my_symb.setColor(QtGui.QColor("#e31a1c")) my_symb.setSize(1.2) center_pt_layer.setRendererV2(QgsSingleSymbolRendererV2(my_symb)) features = [] for nb, pt in enumerate(pts): xo, yo = pt["point"] fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(xo), float(yo)))) fet.setAttributes([nb, 'Origin']) features.append(fet) center_pt_layer.dataProvider().addFeatures(features) QgsMapLayerRegistry.instance().addMapLayer(center_pt_layer)
def add_symbology(self): low_color = self.color_low_value.color() high_color = self.color_high_value.color() index = self.cbx_mode.currentIndex() mode = self.cbx_mode.itemData(index) classes = self.spinBox_classes.value() # Compute renderer # noinspection PyArgumentList symbol = QgsSymbolV2.defaultSymbol(QGis.Polygon) color_ramp = QgsVectorGradientColorRampV2(low_color, high_color) # noinspection PyArgumentList renderer = QgsGraduatedSymbolRendererV2.createRenderer( self.output_layer, self.name_field, classes, mode, symbol, color_ramp) self.output_layer.setRendererV2(renderer)
def add_final_pts(self, pts): center_pt_layer = QgsVectorLayer( "Point?crs=epsg:4326&field=id_center:integer&field=role:string(80)", "isochrone_center_{}".format(self.nb_isocr), "memory") my_symb = QgsSymbolV2.defaultSymbol(0) my_symb.setColor(QtGui.QColor("#e31a1c")) my_symb.setSize(1.2) center_pt_layer.setRendererV2(QgsSingleSymbolRendererV2(my_symb)) features = [] for nb, pt in enumerate(pts): xo, yo = pt["point"] fet = QgsFeature() fet.setGeometry( QgsGeometry.fromPoint(QgsPoint(float(xo), float(yo)))) fet.setAttributes([nb, 'Origin']) features.append(fet) center_pt_layer.dataProvider().addFeatures(features) QgsMapLayerRegistry.instance().addMapLayer(center_pt_layer)
def setGraduatedStyle(vl, ranges, field, **kwargs): """ set a graduated style """ # make a symbol for each range rangeV2List = [] for min_val, max_val, attrs in ranges: if 'label' in attrs: label = attrs['label'] #elif min_val == None: # label = u'%s <= %s' % (field, max_val) #elif max_val == None: # label = u'%s > %s' % (field, min_val) else: label = u'%s < %s <= %s' % (min_val, field, max_val) symbolV2 = QgsSymbolV2.defaultSymbol(vl.geometryType()) if 'color' in attrs: symbolV2.setColor(attrs['color']) if 'size' in attrs: symbolV2.setSize(attrs['size']) # from QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter if 'sizeScaleMethod' in kwargs and hasattr(symbolV2, 'setScaleMethod'): symbolV2.setScaleMethod(kwargs['sizeScaleMethod']) rangeV2 = QgsRendererRangeV2(min_val, max_val, symbolV2, label) rangeV2List.append(rangeV2) # create the renderer renderer = QgsGraduatedSymbolRendererV2(field, rangeV2List) # set size scale field if 'sizeScaleField' in kwargs: renderer.setSizeScaleField(kwargs['sizeScaleField']) # set the renderer for the layer vl.setRendererV2(renderer) Utils.iface.legendInterface().refreshLayerSymbology(vl)
def setGraduatedStyle(vl, ranges, field, **kwargs): """ set a graduated style """ # make a symbol for each range rangeV2List = [] for min_val, max_val, attrs in ranges: if 'label' in attrs: label = attrs['label'] #elif min_val == None: # label = u'%s <= %s' % (field, max_val) #elif max_val == None: # label = u'%s > %s' % (field, min_val) else: label = u'%s < %s <= %s' % (min_val, field, max_val) symbolV2 = QgsSymbolV2.defaultSymbol( vl.geometryType() ) if 'color' in attrs: symbolV2.setColor( attrs['color'] ) if 'size' in attrs: symbolV2.setSize( attrs['size'] ) # from QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter if 'sizeScaleMethod' in kwargs and hasattr(symbolV2, 'setScaleMethod'): symbolV2.setScaleMethod( kwargs['sizeScaleMethod'] ) rangeV2 = QgsRendererRangeV2(min_val, max_val, symbolV2, label) rangeV2List.append(rangeV2) # create the renderer renderer = QgsGraduatedSymbolRendererV2( field, rangeV2List ) # set size scale field if 'sizeScaleField' in kwargs: renderer.setSizeScaleField( kwargs['sizeScaleField'] ) # set the renderer for the layer vl.setRendererV2( renderer ) Utils.iface.legendInterface().refreshLayerSymbology(vl)
def setSimpleStyle(vl, **kwargs): """ set a simple style """ symbolV2 = QgsSymbolV2.defaultSymbol( vl.geometryType() ) if 'color' in kwargs: symbolV2.setColor( kwargs['color'] ) size = kwargs.get('size', None) if 'size' in kwargs: symbolV2.setSize( kwargs['size'] ) # in QGis > 1.8 QgsMarkerSymbolV2 has 2 scale methods: ScaleArea and ScaleDiameter if 'sizeScaleMethod' in kwargs and hasattr(symbolV2, 'setScaleMethod'): symbolV2.setScaleMethod( kwargs['sizeScaleMethod'] ) # create the renderer renderer = QgsSingleSymbolRendererV2( symbolV2 ) # set size scale field if 'sizeScaleField' in kwargs: renderer.setSizeScaleField( kwargs['sizeScaleField'] ) # set the renderer for the layer vl.setRendererV2( renderer ) Utils.iface.legendInterface().refreshLayerSymbology(vl)
def set_vector_graduated_style(vector_layer, style): """Set graduated QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The calling function should take care to scale the transparency level to between 0 and 100. :param vector_layer: A QGIS vector layer that will be styled. :type vector_layer: QgsVectorLayer, QgsMapLayer :param style: Dictionary of the form as in the example below :type style: dict :returns: None - Sets and saves style for vector_layer Example style:: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c', 'min': 0.5, 'label': '[0.5 - 1.5] Low damage', 'size' : 1}, {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c', 'min': 1.5, 'label': '[1.5 - 2.5] Medium damage', 'size' : 1}, {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c', 'min': 2.5, 'label': '[2.5 - 3.5] High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. .. note:: you can optionally pass border_color also, if not color will be used .. note:: you can optionally pass data_defined also, this has to be a dictionary of property: expressions like {'color': 'color_hsv(%s, "pop"/%s*100, %s)' % (hue, max, val)} """ target_field = style['target_field'] style_classes = style['style_classes'] geometry_type = vector_layer.geometryType() range_list = [] for style_class in style_classes: # Transparency 100: transparent # Transparency 0: opaque size = 2 # mm if 'size' in style_class: size = style_class['size'] transparency_percent = 0 if 'transparency' in style_class: transparency_percent = style_class['transparency'] if 'min' not in style_class: raise StyleError('Style info should provide a "min" entry') if 'max' not in style_class: raise StyleError('Style info should provide a "max" entry') try: min_val = float(style_class['min']) except TypeError: raise StyleError( 'Class break lower bound should be a number.' 'I got %s' % style_class['min']) try: max_val = float(style_class['max']) except TypeError: raise StyleError('Class break upper bound should be a number.' 'I got %s' % style_class['max']) color = style_class['colour'] label = style_class['label'] color = QtGui.QColor(color) # noinspection PyArgumentList symbol = QgsSymbolV2.defaultSymbol(geometry_type) # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise # noinspection PyArgumentList try: value = style_class['border_color'] border_color = QtGui.QColor(value) except KeyError: border_color = color if geometry_type == QGis.Point: symbol_layer = QgsSimpleMarkerSymbolLayerV2() symbol_layer.setBorderColor(border_color) symbol_layer.setSize(size) symbol.changeSymbolLayer(0, symbol_layer) elif geometry_type == QGis.Polygon: symbol_layer = QgsSimpleFillSymbolLayerV2() symbol_layer.setBorderColor(border_color) symbol.changeSymbolLayer(0, symbol_layer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass try: value = style_class['border_wdth'] symbol_layer.setBorderWidth(value) except (NameError, KeyError): # use QGIS default border size # NameError is when symbol_layer is not defined (lines for example) # KeyError is when borderWidth is not defined if hasattr(symbol_layer, 'setBorderWidth') and \ geometry_type == QGis.Polygon: symbol_layer.setBorderWidth(0) # set data defined properties try: for prop, expr in style_class['data_defined'].iteritems(): symbol_layer.setDataDefinedProperty(prop, expr) except (NameError, KeyError): # NameError is when symbol_layer is not defined (lines for example) # KeyError is when data_defined is not defined pass symbol.setColor(color) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - transparency_percent / 100.0 symbol.setAlpha(alpha) range_renderer = QgsRendererRangeV2(min_val, max_val, symbol, label) range_list.append(range_renderer) renderer = QgsGraduatedSymbolRendererV2('', range_list) renderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) renderer.setClassAttribute(target_field) vector_layer.setRendererV2(renderer) vector_layer.saveDefaultStyle()
def set_vector_categorized_style(vector_layer, style): """Set categorized QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The calling function should take care to scale the transparency level to between 0 and 100. :param vector_layer: A QGIS vector layer that will be styled. :type vector_layer: QgsVectorLayer :param style: Dictionary of the form as in the example below. :type style: dict :returns: None - Sets and saves style for vector_layer Example:: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'value': 1, 'colour': '#fecc5c', 'label': 'Low damage', 'size' : 1}, {'transparency': 55, 'value': 2, 'colour': '#fd8d3c', 'label': 'Medium damage', 'size' : 1}, {'transparency': 80, 'value': 3, 'colour': '#f31a1c', 'label': 'High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. .. note:: We should change 'value' in style classes to something more meaningful e.g. discriminant value .. note:: you can optionally pass border_color also, if not color will be used .. note:: you can optionally pass border_width also, if not QGIS defaults will be used .. note:: you can optionally pass data_defined also, this has to be a dictionary of property: expressions like {'color': 'color_hsv(%s, "pop"/%s*100, %s)' % (hue, max, val)} """ target_field = style['target_field'] style_classes = style['style_classes'] geometry_type = vector_layer.geometryType() category_list = [] for style_class in style_classes: # Transparency 100: transparent # Transparency 0: opaque size = 2 # mm if 'size' in style_class: size = style_class['size'] transparency_percent = 0 if 'transparency' in style_class: transparency_percent = style_class['transparency'] if 'value' not in style_class: raise StyleError('Style info should provide a "value" entry') value = style_class['value'] colour = style_class['colour'] label = style_class['label'] colour = QtGui.QColor(colour) try: border_color = QtGui.QColor(style_class['border_color']) except KeyError: border_color = colour # noinspection PyArgumentList symbol = QgsSymbolV2.defaultSymbol(geometry_type) # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise # noinspection PyArgumentList if geometry_type == QGis.Point: symbol_layer = QgsSimpleMarkerSymbolLayerV2() symbol_layer.setBorderColor(border_color) symbol_layer.setSize(size) symbol.changeSymbolLayer(0, symbol_layer) elif geometry_type == QGis.Polygon: symbol_layer = QgsSimpleFillSymbolLayerV2() symbol_layer.setBorderColor(border_color) symbol.changeSymbolLayer(0, symbol_layer) else: # for lines we do nothing special as the property setting # below should give us what we require. symbol_layer = None try: symbol_layer.setBorderWidth(style_class['border_width']) except (NameError, KeyError, AttributeError): # use QGIS default border size # NameError is when symbol_layer is not defined (lines for example) # KeyError is when border_width is not defined # AttributeError is when setBorderWidth is not defined # (QgsSimpleMarkerSymbolLayerV2) if hasattr(symbol_layer, 'setBorderWidth') and \ geometry_type == QGis.Polygon: symbol_layer.setBorderWidth(0) # set data defined properties try: for prop, expr in style_class['data_defined'].iteritems(): symbol_layer.setDataDefinedProperty(prop, expr) except (NameError, KeyError): # NameError is when symbol_layer is not defined (lines for example) # KeyError is when data_defined is not defined pass symbol.setColor(colour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - transparency_percent / 100.0 symbol.setAlpha(alpha) category = QgsRendererCategoryV2(value, symbol, label) category_list.append(category) renderer = QgsCategorizedSymbolRendererV2('', category_list) renderer.setClassAttribute(target_field) vector_layer.setRendererV2(renderer) vector_layer.saveDefaultStyle()
def addMemoryLayer(self): '''Adds a layer to contain the feature defined by a bounding box, wkt, digitised poly|line|point or selection from other layer. ''' foi_type = self.foi_type.lower() if foi_type == 'areaofinterestdefiner': layer = QgsVectorLayer("Polygon", "Area of Interest", "memory") if foi_type == 'lineofinterestdefiner': layer = QgsVectorLayer("Linestring", "Line of Interest", "memory") if foi_type == 'pointofinterestdefiner': layer = QgsVectorLayer("Point", "Point of Interest", "memory") if foi_type == 'areaofinterestdefiner': sym = QgsSymbol(QGis.Polygon) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.Dense6Pattern) sym.setLineWidth(0.5) sr = QgsSingleSymbolRenderer(QGis.Polygon) if foi_type == 'lineofinterestdefiner': sym = QgsSymbol(QGis.Line) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.SolidPattern) sym.setLineWidth(0.5) sr = QgsSingleSymbolRenderer(QGis.Line) if foi_type == 'pointofinterestdefiner': sym = QgsSymbol(QGis.Point) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.SolidPattern) sym.setLineWidth(0.3) sym.setPointSize(4) sym.setNamedPointSymbol("hard:triangle") sr = QgsSingleSymbolRenderer(QGis.Point) sr.addSymbol(sym) layer.setRenderer(sr) if not layer.isValid(): print "invalid layer" return ml_dp = layer.dataProvider() ml_dp.addAttributes([QgsField("gid", QtCore.QVariant.String)]) # add layer to the registry self.mem_layer_obj = QgsMapLayerRegistry.instance().addMapLayer(layer) # set extent to the extent of our layer #self.canvas.setExtent(layer.extent()) # set the map canvas layer set cl = QgsMapCanvasLayer(layer) self.mapCanvasLayers.insert(0, cl) #layers = [cl] self.canvas.setLayerSet(self.mapCanvasLayers) print "added Layer"
def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer( self.current_layers[0] ) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert(schema) # Disconnect signals previously connected upon calling this function # The first time this function is called will throw an error because no # previous connections to the slots were made try: #print "Disconnecting ..." self.q_view_dlg.tblw.itemChanged.disconnect() self.q_view_dlg.diffmode_chk.stateChanged.disconnect() except: #print "Failed disconnection" pass # Make sure combobox is initalized correctly self.q_view_dlg.diffmode_chk.setCheckState(Qt.Unchecked) self.q_view_dlg.diffmode_chk.setEnabled(False) pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) ) pcur.execute("SELECT rev, author, date::timestamp(0), branch, commit_msg " "FROM "+schema+".revisions ORDER BY rev ASC") revs = pcur.fetchall() pcur.close() self.q_view_dlg.tblw.setRowCount(len(revs)) self.q_view_dlg.tblw.setColumnCount(5) self.q_view_dlg.tblw.setHorizontalHeaderLabels(['Rev#', 'Author', 'Date', 'Branch', 'Commit Message']) for i, rev in enumerate(revs): for j, item in enumerate(rev): self.q_view_dlg.tblw.setItem(i,j,QTableWidgetItem( str(item) )) # set rev# checkable if j == 0: self.q_view_dlg.tblw.item(i,j).setCheckState(Qt.Unchecked) self.q_view_dlg.tblw.itemChanged.connect(self.enable_diffmode) self.q_view_dlg.tblw.resizeRowsToContents() self.q_view_dlg.tblw.resizeColumnsToContents() self.q_view_dlg.diffmode_chk.stateChanged.connect(self.check_branches) if not self.q_view_dlg.exec_(): return rows = set() revision_number_list = [] branches = [] for i in range(len(revs)): if self.q_view_dlg.tblw.item(i,0).checkState(): print "Revision "+ self.q_view_dlg.tblw.item(i,0).text() +" will be fetched" revision_number_list.append(int(self.q_view_dlg.tblw.item(i,0).text())) branches.append(self.q_view_dlg.tblw.item(i,3).text()) rows.add(self.q_view_dlg.tblw.item(i,0).row()) progressMessageBar = self.iface.messageBar().createMessage("Querying " "the database for revision(s) "+str(revision_number_list)) progress = QProgressBar() progress.setMaximum(len(rows)) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) progress.setValue(0) # if diffmode, create one layer with feature differences between the # two revisions; else checkout the full data sets for the specified # revisions and put them in separate layers (original behaviour) rev_begin = 0 rev_end = 0 empty_layers = [] grp_name='' if self.q_view_dlg.diffmode_chk.isChecked(): print "Diffmode checked" # revision_number_list necessarily has only two items in diffmode rev_begin = revision_number_list[0] rev_end = revision_number_list[1] if rev_begin > rev_end: rev_begin, rev_end = rev_end, rev_begin # if the two revisions are not on the same branch, exit if revs[rev_begin - 1][3] != revs[rev_end - 1][3]: print "Revisions are not on the same branch, exiting" #print "Rev_begin " + str(rev_begin) + " is on " + revs[rev_begin - 1][3] #print "Rev_end " + str(rev_end) + " is on " + revs[rev_end - 1][3] return else : print "Revisions are on the same branch" #print "Rev_begin " + str(rev_begin) + " is on " + revs[rev_begin - 1][3] #print "Rev_end " +str(rev_end) + " is on " + revs[rev_end - 1][3] grp_name = "Compare revisions "+str(rev_begin)+" vs "+ str(rev_end) grp_idx = self.iface.legendInterface().addGroup( grp_name ) for i, layer_id in enumerate(reversed(self.current_layers)): progress.setValue(i+1) layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) select_str = versioning_base.diff_rev_view_str( uri.connectionInfo(), schema, new_uri.table(), branches[0], rev_begin, rev_end ) # change data source uri to point to select sql # schema needs to be set to empty new_uri.setDataSource("", "("+select_str+")", new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() #print "new_uri.uri() = " + new_uri.uri() tmp_pg_layer = self.iface.addVectorLayer( new_uri.uri(), display_name, 'postgres') #print "Number of features in layer " + display_name + " = " + str(tmp_pg_layer.featureCount()) # if layer has no feature, delete tmp layer and resume for loop if not(tmp_pg_layer.featureCount()): QgsMapLayerRegistry.instance().removeMapLayer( tmp_pg_layer.id() ) empty_layers.append(str(display_name)) continue mem_uri = self.mem_layer_uri(tmp_pg_layer) #print "mem_uri = " + mem_uri if mem_uri == "Unknown": return new_mem_layer = self.iface.addVectorLayer( mem_uri, display_name + '_diff', 'memory') pr = new_mem_layer.dataProvider() source_layer_features = [f for f in tmp_pg_layer.getFeatures()] #print "Got features from source vector layer" QgsMapLayerRegistry.instance().removeMapLayer( tmp_pg_layer.id() ) #print "Removed tmp layer" pr.addFeatures(source_layer_features) #print "Copied source features to mem layer" # Style layer to show features as a function of whether they were # - added/created ('a') # - updated ('u') # - deleted ('d') # For all feature types, so do once # Code from http://snorf.net/blog/2014/03/04/symbology-of-vector-layers-in-qgis-python-plugins # For colors, use the names at http://www.w3schools.com/HTML/html_colornames.asp, but lowercase only; tested with "aliceblue" # define some rules: label, expression, color name, size, (min scale, max scale) modification_type_rules = ( ('Intermediate', '"diff_status" LIKE \'i\'', 'aliceblue', 2.0, None), ('Created', '"diff_status" LIKE \'a\'', 'chartreuse', 3.0, None), ('Updated', '"diff_status" LIKE \'u\'', 'sandybrown', 3.0, None), ('Deleted', '"diff_status" LIKE \'d\'', 'red', 3.0, None),) symbol = QgsSymbolV2.defaultSymbol(new_mem_layer.geometryType()) renderer = QgsRuleBasedRendererV2(symbol) root_rule = renderer.rootRule() for label, expression, color_name, size, scale in modification_type_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(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color_name)) ##rule.symbol().setSize(size) # works only for POINT layers # set the scale limits if they have been specified ##if scale is not None: ## rule.setScaleMinDenom(scale[0]) ## rule.setScaleMaxDenom(scale[1]) # append the rule to the list of rules root_rule.appendChild(rule) # delete the default rule root_rule.removeChildAt(0) new_mem_layer.setRendererV2(renderer) # refresh map and legend self.iface.mapCanvas().refresh() self.iface.legendInterface().refreshLayerSymbology(new_mem_layer) self.iface.legendInterface().moveLayer( new_mem_layer, grp_idx) else: print "Diffmode unchecked" for i, row in enumerate(rows): progress.setValue(i+1) branch = revs[row][3] rev = revs[row][0] grp_name = branch+' revision '+str(rev) grp_idx = self.iface.legendInterface().addGroup( grp_name ) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) select_str, where_str = versioning_base.rev_view_str( self.pg_conn_info(), schema, new_uri.table(), branches[0], rev) new_uri.setSql(where_str) new_uri.setDataSource("", "("+select_str+")", new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() src = new_uri.uri().replace('()','') new_layer = self.iface.addVectorLayer( src, display_name, 'postgres') self.iface.legendInterface().moveLayer( new_layer, grp_idx) self.iface.messageBar().clearWidgets() #print "len (self.current_layers) = " + str(len (self.current_layers)) #print "len(empty_layers) = " + str(len(empty_layers)) if empty_layers and len(empty_layers) == len (self.current_layers): print "No layers in layer group" self.iface.messageBar().pushMessage("Notice", "No layers will be shown; deleted the \"" +grp_name +"\" layer group", level=QgsMessageBar.WARNING, duration = 15) self.iface.legendInterface().removeGroup(grp_idx) elif empty_layers : print "Empty layers" self.iface.messageBar().pushMessage("Notice", "No modified features between revisions "+str(rev_begin)+" " "and "+str(rev_end)+" for layer(s) "+str(empty_layers)+". ", level=QgsMessageBar.WARNING, duration = 15)
def setVectorStyle(theQgisVectorLayer, theStyle): """Set QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The function should take care to scale the transparency level to between 0 and 100. Args: * theQgisVectorLayer: QgsMapLayer * theStyle: dict - Dictionary of the form as in the example below Returns: None - Sets and saves style for theQgisVectorLayer Raises: None Example: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c', 'min': 0.5, 'label': 'Low damage', 'size' : 1}, {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c', 'min': 1.5, 'label': 'Medium damage', 'size' : 1}, {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c', 'min': 2.5, 'label': 'High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. """ myTargetField = theStyle['target_field'] myClasses = theStyle['style_classes'] myGeometryType = theQgisVectorLayer.geometryType() myRangeList = [] for myClass in myClasses: # Transparency 100: transparent # Transparency 0: opaque mySize = 2 # mm if 'size' in myClass: mySize = myClass['size'] myTransparencyPercent = 0 if 'transparency' in myClass: myTransparencyPercent = myClass['transparency'] if 'min' not in myClass: raise StyleError('Style info should provide a "min" entry') if 'max' not in myClass: raise StyleError('Style info should provide a "max" entry') try: myMin = float(myClass['min']) except TypeError: raise StyleError('Class break lower bound should be a number.' 'I got %s' % myClass['min']) try: myMax = float(myClass['max']) except TypeError: raise StyleError('Class break upper bound should be a number.' 'I got %s' % myClass['max']) myColour = myClass['colour'] myLabel = myClass['label'] myColour = QtGui.QColor(myColour) mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType) myColourString = "%s, %s, %s" % ( myColour.red(), myColour.green(), myColour.blue()) # Work around for the fact that QgsSimpleMarkerSymbolLayerV2 # python bindings are missing from the QGIS api. # .. see:: http://hub.qgis.org/issues/4848 # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise myRegistry = QgsSymbolLayerV2Registry.instance() if myGeometryType == QGis.Point: myMetadata = myRegistry.symbolLayerMetadata('SimpleMarker') # note that you can get a list of available layer properties # that you can set by doing e.g. # QgsSimpleMarkerSymbolLayerV2.properties() mySymbolLayer = myMetadata.createSymbolLayer({'color_border': myColourString}) mySymbolLayer.setSize(mySize) mySymbol.changeSymbolLayer(0, mySymbolLayer) elif myGeometryType == QGis.Polygon: myMetadata = myRegistry.symbolLayerMetadata('SimpleFill') mySymbolLayer = myMetadata.createSymbolLayer({'color_border': myColourString}) mySymbol.changeSymbolLayer(0, mySymbolLayer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass mySymbol.setColor(myColour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - myTransparencyPercent / 100.0 mySymbol.setAlpha(alpha) myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel) myRangeList.append(myRange) myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList) myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) myRenderer.setClassAttribute(myTargetField) theQgisVectorLayer.setRendererV2(myRenderer) theQgisVectorLayer.saveDefaultStyle()
def setVectorStyle(theQgisVectorLayer, style): """Set QGIS vector style based on InaSAFE style dictionary Input theQgisVectorLayer: Qgis layer style: Dictionary of the form as in the example below {'target_field': 'DMGLEVEL', 'style_classes': [{'opacity': 1, 'max': 1.5, 'colour': '#fecc5c', 'min': 0.5, 'label': 'Low damage', 'size' : 1}, {'opacity': 1, 'max': 2.5, 'colour': '#fd8d3c', 'min': 1.5, 'label': 'Medium damage', 'size' : 1}, {'opacity': 1, 'max': 3.5, 'colour': '#f31a1c', 'min': 2.5, 'label': 'High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. Output Sets and saves style for theQgisVectorLayer """ myTargetField = style["target_field"] myClasses = style["style_classes"] myGeometryType = theQgisVectorLayer.geometryType() myRangeList = [] for myClass in myClasses: # Transparency 100: transparent # Transparency 0: opaque mySize = 2 # mm if "size" in myClass: mySize = myClass["size"] myTransparencyPercent = 0 if "transparency" in myClass: myTransparencyPercent = myClass["transparency"] myMax = myClass["max"] myMin = myClass["min"] myColour = myClass["colour"] myLabel = myClass["label"] myColour = QtGui.QColor(myColour) mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType) myColourString = "%s, %s, %s" % (myColour.red(), myColour.green(), myColour.blue()) # Work around for the fact that QgsSimpleMarkerSymbolLayerV2 # python bindings are missing from the QGIS api. # .. see:: http://hub.qgis.org/issues/4848 # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise myRegistry = QgsSymbolLayerV2Registry.instance() if myGeometryType == QGis.Point: myMetadata = myRegistry.symbolLayerMetadata("SimpleMarker") # note that you can get a list of available layer properties # that you can set by doing e.g. # QgsSimpleMarkerSymbolLayerV2.properties() mySymbolLayer = myMetadata.createSymbolLayer({"color_border": myColourString}) mySymbolLayer.setSize(mySize) mySymbol.changeSymbolLayer(0, mySymbolLayer) elif myGeometryType == QGis.Polygon: myMetadata = myRegistry.symbolLayerMetadata("SimpleFill") mySymbolLayer = myMetadata.createSymbolLayer({"color_border": myColourString}) mySymbol.changeSymbolLayer(0, mySymbolLayer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass mySymbol.setColor(myColour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - myTransparencyPercent / 100 mySymbol.setAlpha(alpha) myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel) myRangeList.append(myRange) myRenderer = QgsGraduatedSymbolRendererV2("", myRangeList) myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) myRenderer.setClassAttribute(myTargetField) theQgisVectorLayer.setRendererV2(myRenderer) theQgisVectorLayer.saveDefaultStyle()
def set_vector_categorized_style(vector_layer, style): """Set categorized QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The calling function should take care to scale the transparency level to between 0 and 100. :param vector_layer: A QGIS vector layer that will be styled. :type vector_layer: QgsVectorLayer :param style: Dictionary of the form as in the example below. :type style: dict :returns: None - Sets and saves style for vector_layer Example:: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'value': 1, 'colour': '#fecc5c', 'label': 'Low damage', 'size' : 1}, {'transparency': 55, 'value': 2, 'colour': '#fd8d3c', 'label': 'Medium damage', 'size' : 1}, {'transparency': 80, 'value': 3, 'colour': '#f31a1c', 'label': 'High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. .. note:: We should change 'value' in style classes to something more meaningful e.g. discriminant value """ myTargetField = style["target_field"] myClasses = style["style_classes"] geometry_type = vector_layer.geometryType() category_list = [] for myClass in myClasses: # Transparency 100: transparent # Transparency 0: opaque mySize = 2 # mm if "size" in myClass: mySize = myClass["size"] myTransparencyPercent = 0 if "transparency" in myClass: myTransparencyPercent = myClass["transparency"] if "value" not in myClass: raise StyleError('Style info should provide a "value" entry') try: myValue = float(myClass["value"]) except TypeError: raise StyleError("Value should be a number. I got %s" % myClass["value"]) colour = myClass["colour"] label = myClass["label"] colour = QtGui.QColor(colour) # noinspection PyArgumentList symbol = QgsSymbolV2.defaultSymbol(geometry_type) # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise # noinspection PyArgumentList if geometry_type == QGis.Point: symbol_layer = QgsSimpleMarkerSymbolLayerV2() symbol_layer.setBorderColor(colour) symbol_layer.setSize(mySize) symbol.changeSymbolLayer(0, symbol_layer) elif geometry_type == QGis.Polygon: symbol_layer = QgsSimpleFillSymbolLayerV2() symbol_layer.setBorderColor(colour) symbol.changeSymbolLayer(0, symbol_layer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass symbol.setColor(colour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - myTransparencyPercent / 100.0 symbol.setAlpha(alpha) category = QgsRendererCategoryV2(myValue, symbol, label) category_list.append(category) renderer = QgsCategorizedSymbolRendererV2("", category_list) renderer.setClassAttribute(myTargetField) vector_layer.setRendererV2(renderer) vector_layer.saveDefaultStyle()
def set_vector_graduated_style(vector_layer, style): """Set graduated QGIS vector style based on InaSAFE style dictionary. For **opaque** a value of **0** can be used. For **fully transparent**, a value of **100** can be used. The calling function should take care to scale the transparency level to between 0 and 100. :param vector_layer: A QGIS vector layer that will be styled. :type vector_layer: QgsVectorLayer :param style: Dictionary of the form as in the example below :type style: dict :returns: None - Sets and saves style for vector_layer Example style:: {'target_field': 'DMGLEVEL', 'style_classes': [{'transparency': 1, 'max': 1.5, 'colour': '#fecc5c', 'min': 0.5, 'label': '[0.5 - 1.5] Low damage', 'size' : 1}, {'transparency': 55, 'max': 2.5, 'colour': '#fd8d3c', 'min': 1.5, 'label': '[1.5 - 2.5] Medium damage', 'size' : 1}, {'transparency': 80, 'max': 3.5, 'colour': '#f31a1c', 'min': 2.5, 'label': '[2.5 - 3.5] High damage', 'size' : 1}]} .. note:: The transparency and size keys are optional. Size applies to points only. """ myTargetField = style["target_field"] myClasses = style["style_classes"] myGeometryType = vector_layer.geometryType() myRangeList = [] for myClass in myClasses: # Transparency 100: transparent # Transparency 0: opaque mySize = 2 # mm if "size" in myClass: mySize = myClass["size"] myTransparencyPercent = 0 if "transparency" in myClass: myTransparencyPercent = myClass["transparency"] if "min" not in myClass: raise StyleError('Style info should provide a "min" entry') if "max" not in myClass: raise StyleError('Style info should provide a "max" entry') try: myMin = float(myClass["min"]) except TypeError: raise StyleError("Class break lower bound should be a number." "I got %s" % myClass["min"]) try: myMax = float(myClass["max"]) except TypeError: raise StyleError("Class break upper bound should be a number." "I got %s" % myClass["max"]) myColour = myClass["colour"] myLabel = myClass["label"] myColour = QtGui.QColor(myColour) # noinspection PyArgumentList mySymbol = QgsSymbolV2.defaultSymbol(myGeometryType) # We need to create a custom symbol layer as # the border colour of a symbol can not be set otherwise # noinspection PyArgumentList if myGeometryType == QGis.Point: mySymbolLayer = QgsSimpleMarkerSymbolLayerV2() mySymbolLayer.setBorderColor(myColour) mySymbolLayer.setSize(mySize) mySymbol.changeSymbolLayer(0, mySymbolLayer) elif myGeometryType == QGis.Polygon: mySymbolLayer = QgsSimpleFillSymbolLayerV2() mySymbolLayer.setBorderColor(myColour) mySymbol.changeSymbolLayer(0, mySymbolLayer) else: # for lines we do nothing special as the property setting # below should give us what we require. pass mySymbol.setColor(myColour) # .. todo:: Check that vectors use alpha as % otherwise scale TS # Convert transparency % to opacity # alpha = 0: transparent # alpha = 1: opaque alpha = 1 - myTransparencyPercent / 100.0 mySymbol.setAlpha(alpha) myRange = QgsRendererRangeV2(myMin, myMax, mySymbol, myLabel) myRangeList.append(myRange) myRenderer = QgsGraduatedSymbolRendererV2("", myRangeList) myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) myRenderer.setClassAttribute(myTargetField) vector_layer.setRendererV2(myRenderer) vector_layer.saveDefaultStyle()
def run(self): """Run method that performs all the real work""" self.dlg.layerComboBox.clear() self.dlg.sheetTypeComboBox.clear() self.dlg.scaleComboBox.clear() #self.dlg.label_2.setText('') Alllayers = self.iface.legendInterface().layers() #layer_list = [] lcount=0 for layer in Alllayers: xyCrs = layer.crs() if xyCrs.projectionAcronym()=='longlat': lcount=lcount+1 self.dlg.layerComboBox.addItem(layer.name(),layer) self.dlg.sheetTypeComboBox.addItem('Indian and Adjoining Countries Series Maps') self.dlg.sheetTypeComboBox.addItem('Open Series Maps') scale_list=['1:1M','1:250,000','1:125,000','1:50,000','1:25,000'] self.dlg.scaleComboBox.addItems(scale_list) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: global scaleID global sheetw global sheeth if lcount>0: scaleID=self.dlg.scaleComboBox.currentIndex()+1 maptype= self.dlg.sheetTypeComboBox.currentIndex()+1 if maptype==1: sheetw,sheeth=setFactor1(scaleID) if maptype==2: sheetw,sheeth=setFactor2(scaleID) index = self.dlg.layerComboBox.currentIndex() clayer = self.dlg.layerComboBox.itemData(index) e=clayer.extent() a,b,c=degDec2dms(e.xMinimum()) slongs=dmstosec(a,b,c) a,b,c=degDec2dms(e.xMaximum()) elongs=dmstosec(a,b,c) a,b,c=degDec2dms(e.yMinimum()) slats=dmstosec(a,b,c) a,b,c=degDec2dms(e.yMaximum()) elats=dmstosec(a,b,c) slongs,elongs,slats,elats=CalculateExtentInTermsOfSheet(slongs,elongs,slats,elats) Xgrids=int(elongs-slongs)//sheetw # // is used for modular division Ygrids=int(elats-slats)//sheeth layer = QgsVectorLayer("Polygon?crs=EPSG:4326", "TopoSheets", "memory") global poly global pr pr = layer.dataProvider() pr.addAttributes([QgsField("id",QVariant.Int),QgsField("SheetNo",QVariant.String),QgsField("Inside",QVariant.String)]) layer.updateFields() poly = QgsFeature() CalculateSheet(maptype,slats,slongs,Xgrids,Ygrids) n=0 # check intersection of selected layer feature with sheets fieldIdx = pr.fields().indexFromName('Inside' ) updateMap = {} for f in clayer.getFeatures(): for a in layer.getFeatures(): if a.geometry().intersects(f.geometry()): n=n+1 updateMap[a.id()] = { fieldIdx:1 } pr.changeAttributeValues(updateMap) # set the layer symbology values = ( ('In', True,True,QColor.fromRgb(95,254,99)), ('Out', False,False,'yellow'), ) # create a category for each item in values ranges=[] for label, lower, upper, color in values: symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(QColor(color)) rng = QgsRendererRangeV2(lower, upper, symbol, label) ranges.append(rng) expression = 'Inside' # field name renderer = QgsGraduatedSymbolRendererV2(expression, ranges) layer.setRendererV2(renderer) # set layer transparence and dolabelling layer.setLayerTransparency(65) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayers([layer]) layer.setCustomProperty("labeling", "pal") layer.setCustomProperty("labeling/enabled", "true") layer.setCustomProperty("labeling/fontFamily", "Arial") layer.setCustomProperty("labeling/fontSize", "10") layer.setCustomProperty("labeling/fieldName", "SheetNo") layer.setCustomProperty("labeling/placement", "1") iface.mapCanvas().refresh() else: iface.messageBar().pushMessage("Error", "No layers loaded, Load layer with Geographic Corrdinates", level=QgsMessageBar.CRITICAL) pass