def update_font_labels(self): layer_font = ( iface.layerTreeView().layerTreeModel().layerTreeNodeFont(QgsLayerTree.NodeLayer) ) self.layer_font_label.setText( f"{layer_font.family()}, {layer_font.pointSize()}" ) self.layer_font_label.setFont(layer_font) text_color = self.settings.value("layer_text_color", "black") background_color = self.settings.value("layer_background_color", "white") if QColor(background_color) == QColor("white"): background_color = "transparent" self.layer_font_label.setStyleSheet( f"color:{text_color}; background-color:{background_color}" ) group_font = ( iface.layerTreeView().layerTreeModel().layerTreeNodeFont(QgsLayerTree.NodeGroup) ) self.group_font_label.setText( f"{group_font.family()}, {group_font.pointSize()}" ) self.group_font_label.setFont(group_font) text_color = self.settings.value("group_text_color", "black") background_color = self.settings.value("group_background_color", "white") if QColor(background_color) == QColor("white"): background_color = "transparent" self.group_font_label.setStyleSheet( f"color:{text_color}; background-color:{background_color}" )
def set_arrows(input_layer): """ Give a spectific symbology to the input layer :param input_layer: A layer :input_layer type: QgsVectorLayer """ # Get the renderer of the layer layer_renderer = input_layer.renderer() # Create symbology marker = { 'interval': '3', 'interval_map_unit_scale': '3x:0,0,0,0,0,0', 'interval_unit': 'MM', 'offset': '0', 'offset_along_line': '0', 'offset_along_line_map_unit_scale': '3x:0,0,0,0,0,0', 'offset_along_line_unit': 'MM', 'offset_map_unit_scale': '3x:0,0,0,0,0,0', 'offset_unit': 'MM', 'placement': 'centralpoint', 'rotate': '1' } arrow = { 'angle': '90', 'color': '255,0,0,255', 'horizontal_anchor_point': '1', 'joinstyle': 'bevel', 'name': 'arrow', 'offset': '0,0', 'offset_map_unit_scale': '3x:0,0,0,0,0,0', 'offset_unit': 'MM', 'outline_color': '35,35,35,255', 'outline_style': 'solid', 'outline_width': '0', 'outline_width_map_unit_scale': '3x:0,0,0,0,0,0', 'outline_width_unit': 'MM', 'scale_method': 'diameter', 'size': '2.5', 'size_map_unit_scale': '3x:0,0,0,0,0,0', 'size_unit': 'MM', 'vertical_anchor_point': '1' } # Assign symbology to symbology holder symbol_layer = QgsMarkerLineSymbolLayer.create(marker) # Get subsymbol subSymbol = symbol_layer.subSymbol() arrow_symbol = QgsSimpleMarkerSymbolLayer.create(arrow) # Delete existing subsymbol subSymbol.deleteSymbolLayer(0) # Append the arrow symbol subSymbol.appendSymbolLayer(arrow_symbol) # Append a new symbology to the renderer of the current layer layer_renderer.symbol().appendSymbolLayer(symbol_layer) # Refresh iface.layerTreeView().refreshLayerSymbology(input_layer.id())
def select_layer_font(self): dialog = ColorFontDialog(iface.mainWindow()) f = QFont() f.fromString(self.settings.value("layer_font")) dialog.setCurrentFont(f) f = iface.layerTreeView().layerTreeModel().layerTreeNodeFont(QgsLayerTree.NodeLayer) dialog.setCurrentFont(f) if self.settings.value("layer_text_color"): dialog.setTextColor(QColor(self.settings.value("layer_text_color"))) if self.settings.value("layer_background_color"): dialog.setBackgroundColor( QColor(self.settings.value("layer_background_color")) ) res = dialog.exec() if res != QDialog.Accepted: return iface.layerTreeView().layerTreeModel().setLayerTreeNodeFont( QgsLayerTree.NodeLayer, dialog.currentFont() ) self.settings.setValue(f"layer_font", dialog.currentFont().toString()) self.settings.setValue("layer_text_color", dialog.textColor().name()) self.settings.setValue( "layer_background_color", dialog.backgroundColor().name() ) self.update_font_labels() dialog.deleteLater()
def slider_function(self, value): layer = self.iface.mapCanvas().currentLayer() #print(layer.renderer().type()) #for field in layer.renderer().symbol().symbolLayer(0): #print(field.name(), field.typeName()) #layer.renderer().symbol().symbolLayer(0).setSize(value) #layer=iface.mapCanvas().currentLayer() #QgsMessageLog.logMessage('stylings opgeslagen', 'datachecker') renderer = layer.renderer() if hasattr(renderer, 'symbol') == False: if hasattr(renderer, 'Rule') == True: root_rule = renderer.rootRule() for rule in root_rule.children(): rule.symbol().setSize(value) elif layer.renderer().symbol().type() == 1: # Lijnen layer.renderer().symbol().symbolLayer(0).setWidth(value) print(layer.renderer().symbol().symbolLayer(0).width()) elif layer.renderer().symbol().type() == 0: # symbolen # newsize = layer.renderer().symbol().symbolLayer(0).size()*5/value layer.renderer().symbol().symbolLayer(0).setSize(value) print(layer.renderer().symbol().symbolLayer(0).size()) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) print(layer.name())
def onStyle(self): """Apply new style for currently selected layer. Show error message dialog on failure. """ layer = self.getActiveLayer() if not layer: # no layer is currently selected, nothing to do return # apply new style on currently selected layer try: layer.setStyle(self.styleBox.currentIndex()) layer.setAliases() # loadNameStyle removes aliases (why?) except (RadiationToolboxError, StyleError) as e: # print error message on failure QtWidgets.QMessageBox.critical( None, self.tr("Error"), self.tr("Failed to apply style: {0}").format(e), QtWidgets.QMessageBox.Abort) node = QgsProject.instance().layerTreeRoot().findLayer(layer.id()) iface.layerTreeView().layerTreeModel().refreshLayerLegend(node) # If caching is enabled, a simple canvas refresh might not be sufficient # to trigger a redraw and you must clear the cached image for the layer if iface.mapCanvas().isCachingEnabled(): layer.triggerRepaint() else: iface.mapCanvas().refresh()
def set_icon_from_ressources(self, settings_key): res = self.resource_browser.exec() if res == QDialog.Accepted: button = self.findChild(QToolButton, settings_key) button.setIcon(QIcon(self.resource_browser.icon)) self.settings.setValue( f"defaulticons/{settings_key}", self.resource_browser.icon ) iface.layerTreeView().layerTreeModel().dataChanged.emit(QModelIndex(), QModelIndex())
def postProcessAlgorithm(self, context, feedback): output = QgsProcessingUtils.mapLayerFromString(self.dest_id, context) style_path = os.path.join(os.path.dirname(__file__), 'styles/spi.qml') output.loadNamedStyle(style_path) output.triggerRepaint() iface.mapCanvas().refresh() iface.mapCanvas().refreshAllLayers() iface.layerTreeView().refreshLayerSymbology(output.id()) return {self.OUTPUT: self.dest_id}
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'selec_cidades_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Seleciona Cidades') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None # Adicao das camadas uri = QgsDataSourceUri() uri.setConnection("localhost", "5432", "pyqgis", "postgres", "postgres") uri.setDataSource("public", "mun_sirgas", "geom", "") layer1 = QgsVectorLayer(uri.uri(), "mun_sirgas", "postgres") # Adicionando layer ao prj QgsProject.instance().addMapLayer(layer1) # Atribuindo a simbologia symbol = QgsFillSymbol.createSimple({ 'border_width_map_unit_scale': '3x:0,0,0,0,0,0', 'color': '244,226,196,255', 'joinstyle': 'bevel', 'offset': '0,0', 'offset_map_unit_scale': '3x:0,0,0,0,0,0', 'offset_unit': 'MM', 'outline_color': '175,179,138,255', 'outline_style': 'solid', 'outline_width': '0.26', 'outline_width_unit': 'MM', 'style': 'solid' }) layer1.renderer().setSymbol(symbol) # mostrar as mudancas layer1.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer1.id())
def _addMapLayer(layer): # add map layer to the canvas (do not add into TOC) QgsProject.instance().addMapLayer(layer, False) # force register layer in TOC as a first item QgsProject.instance().layerTreeRoot().insertLayer(0, layer) # select this layer (this must be done manually since we # are inserting item into layer tree) iface.layerTreeView().setCurrentLayer(layer) # expand layer iface.layerTreeView().currentNode().setExpanded(True)
def createWidget(self): if self.dialogType == DIALOG_STANDARD: if iface is not None and iface.layerTreeView() is not None and iface.layerTreeView().layerTreeModel() is not None: iface.layerTreeView().layerTreeModel().dataChanged.connect(self.refresh) return self._panel(self._get_options()) elif self.dialogType == DIALOG_BATCH: return QLineEdit() else: layers = self.dialog.getAvailableValuesOfType([QgsProcessingParameterRasterLayer], [QgsProcessingOutputRasterLayer]) options = {self.dialog.resolveValueDescription(lyr): "{}@1".format(self.dialog.resolveValueDescription(lyr)) for lyr in layers} self.widget = self._panel(options) return self.widget
def switch_layerIsolate(self, value): if value: iface.currentLayerChanged.connect( lambda _: self.switch_visibility()) # iface.layerTreeView().selectionChanged.connect(self.switch_visibility) # QObject.connect(self.iface,SIGNAL("currentLayerChanged(QgsMapLayer *)") ,self.switch_visibility) # QObject.connect(self.iface.mapCanvas(),SIGNAL("selectionChanged(QgsMapLayer)"), self.switch_visibility) else: # iface.currentLayerChanged.disconnect(lambda _: self.switch_visibility) iface.layerTreeView().currentLayerChanged.disconnect( ) #lambda _: self.switch_visibility)
def style_painter(isoBreaks=[0, 2, 5, 10]): qgis_style_files_path = '/Users/Bonny/Documents/Thesis/Hydropolator/qgis_styles/' style_path_isobaths = qgis_style_files_path + 'isobaths' + '.qml' style_path_node_triangles = qgis_style_files_path + 'node_triangles_style' + '.qml' style_path_edge_triangles = qgis_style_files_path + 'edge_triangles_style' + '.qml' style_path_angularities = qgis_style_files_path + 'angularities' + '.qml' print(style_path_isobaths) for layer in QgsProject.instance().mapLayers().values(): if 'edge_triangles' in layer.name(): layer.loadNamedStyle(style_path_edge_triangles) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) elif 'node_triangles' in layer.name(): layer.loadNamedStyle(style_path_node_triangles) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) elif 'isobaths_' in layer.name(): layer.loadNamedStyle(style_path_isobaths) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) elif 'angularities' in layer.name(): layer.loadNamedStyle(style_path_angularities) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) elif 'DEPARE' in layer.name(): color_depares(layer, isoBreaks)
def run(self): """Run method that performs all the real work""" from qgis.core import QgsMarkerSymbol, QgsProject, QgsSymbol from qgis.utils import iface import pandas as pd import time data = pd.read_pickle('C:\\projectData\\blackforest\\data.pickle') # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = FloatingWasteDialog() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: stationLayer = QgsProject.instance().mapLayersByName("SensorStations")[0] stationLayer.setAutoRefreshInterval(500) stationLayer.setAutoRefreshEnabled(True) iface.setActiveLayer(stationLayer) FloatingWaste.setRenderer(layer = stationLayer) iface.layerTreeView().refreshLayerSymbology(stationLayer.id()) stationLayer.startEditing() for i in range(len(data)): print(i) for c in data.columns: index = c - 1 value = data.loc[i,c] wlevel = FloatingWaste.getWasteClass(value) # (ID, 0=id; 1=wlevel; 2=wastecount, value) stationLayer.changeAttributeValue(index, 1, wlevel) stationLayer.changeAttributeValue(index, 2, str(value)) print(f"Station:{index}, Vaule:{value}, Class:{wlevel}") #iface.layerTreeView().refreshLayerSymbology(iface.activeLayer().id()) #iface.layerTreeView().refreshLayerSymbology(stationLayer.id()) FloatingWaste.spin(3)
def set_layer_categoryze(layer, cat_field, size, color_values, unique_values=None): """ :param layer: QgsVectorLayer to be categorized (QgsVectorLayer) :param cat_field: Field to categorize (String) :param size: Size of feature (int) """ # get unique values fields = layer.fields() fni = fields.indexOf(cat_field) if not unique_values: unique_values = layer.dataProvider().uniqueValues(fni) categories = [] 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 try: color = color_values.get(str(unique_value)) symbol.setColor(color) except Exception: color = QColor(randrange(0, 256), randrange(0, 256), randrange(0, 256)) symbol.setColor(color) # 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() iface.layerTreeView().refreshLayerSymbology(layer.id())
def set_icon_from_file(self, settings_key): iconpath = self.settings.value("iconpath", "") icon, _ = QFileDialog.getOpenFileName( caption=self.tr("Select Icon"), filter=self.tr("Image Files (*.svg *.png *.gif);;All files (*)"), directory=iconpath, ) if not icon: return button = self.findChild(QToolButton, settings_key) button.setIcon(QIcon(icon)) self.settings.setValue(f"defaulticons/{settings_key}", icon) iface.layerTreeView().layerTreeModel().dataChanged.emit(QModelIndex(), QModelIndex())
def bulkScreenshot(self): project = QgsProject.instance() root = project.layerTreeRoot() domainGroupName = 'CalvingFronts/Domains/*/*' domainLayers = findChildren(root, domainGroupName) # For each domain in CalvingFronts... # canvas = iface.mapCanvas() numDomain = len(domainLayers) view = iface.layerTreeView() saveDir = r'D:\Daniel\Documents\Github\CALFIN Repo\paper\qgis_screnshots' for i in range(numDomain): self.setProgress((i) / numDomain * 50) domainLayer = domainLayers[i].layer() layerName = domainLayer.name() view.setCurrentLayer(domainLayer) # extent = domainLayer.extent() # print(extent) # canvas.setExtent(extent) iface.actionZoomToLayer() # iface.mapCanvas().refresh() time.sleep(3) savePath = os.path.join( saveDir, 'termini_1972-2019_' + layerName + '_overlay.png') iface.mapCanvas().saveAsImage(savePath) self.setProgress((i + 1) / numDomain * 50)
def set_custom_font(self): """ Set a custom icon as a custom property on the selected nodes """ dialog = ColorFontDialog(iface.mainWindow()) f = iface.layerTreeView().layerTreeModel().layerTreeNodeFont(QgsLayerTree.NodeLayer) for node in self.nodes: if node.customProperty("plugins/customTreeIcon/font"): f.fromString(node.customProperty("plugins/customTreeIcon/font")) text_color = node.customProperty( "plugins/customTreeIcon/textColor", "black" ) background_color = node.customProperty( "plugins/customTreeIcon/backgroundColor", "white" ) dialog.setTextColor(QColor(text_color)) dialog.setBackgroundColor(QColor(background_color)) break dialog.setCurrentFont(f) res = dialog.exec() if res == QDialog.Accepted: for node in self.nodes: node.setCustomProperty( "plugins/customTreeIcon/font", dialog.currentFont().toString() ) node.setCustomProperty( "plugins/customTreeIcon/textColor", dialog.textColor().name() ) node.setCustomProperty( "plugins/customTreeIcon/backgroundColor", dialog.backgroundColor().name(), ) dialog.deleteLater()
def run_clearfilter(self): """Run method that performs the clear filter""" selectedLayers = iface.layerTreeView().selectedLayersRecursive() for layer in selectedLayers: layer.setSubsetString('') layer.triggerRepaint()
def theme_changed(self): theme = self.dockwidget.PresetComboBox.currentText() root = QgsProject.instance().layerTreeRoot() model = iface.layerTreeView().layerTreeModel() QgsProject.instance().mapThemeCollection().applyTheme( theme, root, model )
def run_commit(self): """Run method that performs the commit""" selectedLayers = iface.layerTreeView().selectedLayersRecursive() for layer in selectedLayers: layer.commitChanges() layer.triggerRepaint()
def run_edit(self): """Run method that performs the edit""" selectedLayers = iface.layerTreeView().selectedLayersRecursive() for layer in selectedLayers: layer.startEditing() layer.triggerRepaint()
def rename_maptheme(self): theme = self.dockwidget.PresetComboBox.currentText() quest = QInputDialog.getText(None, self.tr(u'Rename Theme'), self.tr(u'New Name:'), 0, theme ) root = QgsProject.instance().layerTreeRoot() model = iface.layerTreeView().layerTreeModel() name, ok = quest if ok and name != "": rec = QgsProject.instance().mapThemeCollection().createThemeFromCurrentState(root, model) QgsProject.instance().mapThemeCollection().insert(name, rec) self.populate() QgsProject.instance().mapThemeCollection().applyTheme( name, root, model ) QgsProject.instance().mapThemeCollection().removeMapTheme(theme) self.populate() self.theme_changed() self.set_combo_text(name) return else: return
def replace_maptheme(self): theme = self.dockwidget.PresetComboBox.currentText() root = QgsProject.instance().layerTreeRoot() model = iface.layerTreeView().layerTreeModel() rec = QgsProject.instance().mapThemeCollection( ).createThemeFromCurrentState(root, model) QgsProject.instance().mapThemeCollection().update(theme, rec)
def __init__(self, canvas, action): KadasBottomBar.__init__(self, canvas, "orange") self.setupUi(self) self.setStyleSheet("QFrame { background-color: orange; }") self.action = action self.btnClose.setIcon(QIcon(":/kadas/icons/close")) self.btnClose.setToolTip(self.tr('Close TSP dialog')) self.action.toggled.connect(self.actionToggled) self.btnClose.clicked.connect(self.action.toggle) self.btnCalculate.clicked.connect(self.calculate) self.layerSelector = KadasLayerSelectionWidget( canvas, iface.layerTreeView(), lambda x: isinstance(x, OptimalRouteLayer), self.createLayer) self.layerSelector.createLayerIfEmpty("TSP") self.layout().addWidget(self.layerSelector, 0, 0, 1, 2) self.originSearchBox = LocationInputWidget( canvas, locationSymbolPath=iconPath('pin_origin.svg')) self.layout().addWidget(self.originSearchBox, 2, 1) self.destinationSearchBox = LocationInputWidget( canvas, locationSymbolPath=iconPath('pin_destination.svg')) self.layout().addWidget(self.destinationSearchBox, 3, 1) # Set default self.lineEditBuffer.setText('500') self.pushButtonReset.clicked.connect(self.clear)
def run_undo(self): """Run method that performs the undo""" selectedLayers = iface.layerTreeView().selectedLayersRecursive() for layer in selectedLayers: layer.rollBack() layer.triggerRepaint()
def add_widget_to_layer(layer): if is_planet_url(layer.source() ) and PLANET_MOSAICS not in layer.customPropertyKeys(): proc = "default" ramp = "" mosaic = mosaic_name_from_url(layer.source()) if mosaic is not None: tokens = layer.source().split("&") for token in tokens: if token.startswith("url="): subtokens = urllib.parse.unquote(token).split("&") for subtoken in subtokens: if subtoken.startswith("proc="): proc = subtoken.split("=")[1] if subtoken.startswith("ramp="): ramp = subtoken.split("=")[1] datatype = datatype_from_mosaic_name(mosaic) mosaics = [(mosaic, mosaic)] layer.setCustomProperty(PLANET_MOSAIC_PROC, proc) layer.setCustomProperty(PLANET_MOSAIC_RAMP, ramp) layer.setCustomProperty(PLANET_MOSAIC_DATATYPE, datatype) layer.setCustomProperty(PLANET_MOSAICS, json.dumps(mosaics)) layer.setCustomProperty("embeddedWidgets/count", 1) layer.setCustomProperty("embeddedWidgets/0/id", WIDGET_PROVIDER_NAME) view = iface.layerTreeView() view.currentNode().setExpanded(True)
def add_mosaics_to_qgis_project(mosaics, name, proc="default", ramp="", zmin=0, zmax=22, add_xyz_server=False): mosaic_names = [(mosaic_title(mosaic), mosaic[NAME]) for mosaic in mosaics] tile_url = mosaics[0][LINKS][TILES] uri = f'type=xyz&url={tile_url}&zmin={zmin}&zmax={zmax}' layer = QgsRasterLayer(uri, name, 'wms') layer.setCustomProperty(PLANET_CURRENT_MOSAIC, mosaic_title(mosaics[0])) layer.setCustomProperty(PLANET_MOSAIC_PROC, proc) layer.setCustomProperty(PLANET_MOSAIC_RAMP, ramp) layer.setCustomProperty(PLANET_MOSAIC_DATATYPE, mosaics[0][DATATYPE]) layer.setCustomProperty(PLANET_MOSAICS, json.dumps(mosaic_names)) QgsProject.instance().addMapLayer(layer) layer.setCustomProperty("embeddedWidgets/count", 1) layer.setCustomProperty("embeddedWidgets/0/id", WIDGET_PROVIDER_NAME) view = iface.layerTreeView() view.layerTreeModel().refreshLayerLegend(view.currentNode()) view.currentNode().setExpanded(True) if add_xyz_server: s = QSettings() s.setValue(f'qgis/connections-xyz/{name}/zmin', zmin) s.setValue(f'qgis/connections-xyz/{name}/zmax', zmax) s.setValue(f'qgis/connections-xyz/{name}/username', "") s.setValue(f'qgis/connections-xyz/{name}/password', "") s.setValue(f'qgis/connections-xyz/{name}/authcfg', "") procparam = quote(f'&proc={proc}') if proc != "rgb" else "" rampparam = quote(f'&color={ramp}') if ramp else "" full_uri = f"{tile_url}{procparam}{rampparam}" s.setValue(f'qgis/connections-xyz/{name}/url', full_uri.replace(PlanetClient.getInstance().api_key(), ""))
def layers_selected(self) -> bool: """Check if there are any layers selected and populate self.selected_layers. :return: Whether there are any layers selected. """ view = iface.layerTreeView() self.selected_layers = [n for n in view.selectedNodes() if QgsLayerTree.isLayer(n)] return len(self.selected_layers) > 0
def update_symbology(layer: QgsMapLayer, color: typing.Tuple[int, int, int] = None, size: float = None, file: str = None) -> None: assert layer, 'Layer is not defined' if file: assert isinstance(file, str) (msg, noError) = layer.loadNamedStyle(file) if not noError: raise Exception(msg) renderer = layer.renderer() symbol = None if isinstance(renderer, QgsSingleSymbolRenderer): symbol = renderer.symbol() elif isinstance(renderer, QgsGraduatedSymbolRenderer): symbol = renderer.sourceSymbol() else: raise Exception('Unknown renderer!') if color: assert isinstance( color, collections.abc.Sequence ), 'Color should be a iteratable of three numbers for Red, Green, Blue; Each of them between 0 and 255' assert len(color) in ( 3, 4 ), 'There should be three numbers passed for Red, Green, Blue; Each of them between 0 and 255' symbol.setColor(QColor.fromRgb(*color)) if size: # For lines if type(symbol) == QgsLineSymbol: symbol.setWidth(size) # For points if type(symbol) == QgsMarkerSymbol: symbol.setSize(size) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id())
def unset_arrows(input_layer): """ Remove the arrow symbology of the input_layer :param input_layer: A layer :input_layer type: QgsVectorLayer """ # Get the renderer of the layer layer_renderer = input_layer.renderer() # Get the number of symbol layers the layer has nb_sl = layer_renderer.symbol().symbolLayerCount() # Replace the renderer of the current layer layer_renderer.symbol().deleteSymbolLayer(nb_sl - 1) # Refresh iface.layerTreeView().refreshLayerSymbology(input_layer.id())
def add_layer_to_map(ds): layers4add = [] if ds.type.lower() == KNOWN_DRIVERS.TMS.lower(): if ds.alt_tms_urls: tms_url = ds.alt_tms_urls[random.randint(0, len(ds.alt_tms_urls)-1)] else: tms_url = ds.tms_url if PluginSettings.use_native_tms(): # add version check service_url = tms_url.replace("=", "%3D").replace("&", "%26") if ds.tms_y_origin_top is not None and ds.tms_y_origin_top==False: service_url = service_url.replace('{y}', '{-y}') qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format( ds.tms_zmin or TileDefaultSettings.ZMIN, ds.tms_zmax or TileDefaultSettings.ZMAX, service_url ) layer = QgsRasterLayer(qgis_tms_uri, tr(ds.alias), KNOWN_DRIVERS.WMS.lower()) ProjectionHelper.set_tile_layer_proj(layer, ds.tms_epsg_crs_id, ds.tms_postgis_crs_id, ds.tms_custom_proj) layers4add.append(layer) else: service_info = TileServiceInfo(tr(ds.alias), ds.copyright_text, tms_url) service_info.zmin = ds.tms_zmin or service_info.zmin service_info.zmax = ds.tms_zmax or service_info.zmax if ds.tms_y_origin_top is not None: service_info.yOriginTop = ds.tms_y_origin_top service_info.epsg_crs_id = ds.tms_epsg_crs_id service_info.postgis_crs_id = ds.tms_postgis_crs_id service_info.custom_proj = ds.tms_custom_proj if ds.tms_tile_ranges is not None: # needs try block & checks that keys are integers etc.. service_info.tile_ranges = ast.literal_eval(ds.tms_tile_ranges) if ds.tms_tsize1 is not None: service_info.tsize1 = ds.tms_tsize1 if ds.tms_origin_x is not None: service_info.originX = ds.tms_origin_x if ds.tms_origin_y is not None: service_info.originY = ds.tms_origin_y layer = TileLayer(service_info, False) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.GDAL.lower(): layer = QgsRasterLayer(ds.gdal_source_file, tr(ds.alias)) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.WMS.lower(): qgis_wms_uri = u'' if ds.wms_params: qgis_wms_uri += ds.wms_params if ds.wms_layers: layers = ds.wms_layers.split(',') if layers: if ds.wms_turn_over: layers.reverse() qgis_wms_uri += '&layers=' + '&layers='.join(layers) + '&styles=' * len(layers) qgis_wms_uri += '&url=' + ds.wms_url + "?" + ds.wms_url_params.replace("=","%3D").replace("&","%26") layer = QgsRasterLayer(qgis_wms_uri, tr(ds.alias), KNOWN_DRIVERS.WMS.lower()) layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.WFS.lower(): qgis_wfs_uri_base = ds.wfs_url if ds.wfs_params is not None: qgis_wfs_uri_base += ds.wfs_params o = urlparse.urlparse(qgis_wfs_uri_base) request_attrs = dict(urlparse.parse_qsl(o.query)) new_request_attrs = {} for k, v in request_attrs.items(): new_request_attrs[k.upper()] = v if ds.wfs_epsg is not None: new_request_attrs['SRSNAME'] = "EPSG:{0}".format(ds.wfs_epsg) layers = [] if len(ds.wfs_layers) > 0: layers.extend(ds.wfs_layers) else: layers_str = request_attrs.get('TYPENAME', '') layers.extend(layers_str.split()) for layer_name in layers: new_request_attrs['TYPENAME'] = layer_name url_parts = list(o) url_parts[4] = "&".join( ["%s=%s" % (k, v) for k, v in new_request_attrs.items()] ) qgis_wfs_uri = urlparse.urlunparse(url_parts) layer = QgsVectorLayer( qgis_wfs_uri, "%s - %s" % (tr(ds.alias), layer_name), "WFS") layers4add.append(layer) if ds.type.lower() == KNOWN_DRIVERS.GEOJSON.lower(): layer = QgsVectorLayer( ds.geojson_url, tr(ds.alias), "ogr") layers4add.append(layer) for layer in layers4add: if not layer.isValid(): error_message = tr('Layer %s can\'t be added to the map!') % ds.alias iface.messageBar().pushMessage(tr('Error'), error_message, level=QGisMessageBarLevel.Critical) QgsMessageLog.logMessage(error_message, level=QGisMessageLogLevel.Critical) else: # Set attribs layer.setAttribution(ds.copyright_text) layer.setAttributionUrl(ds.copyright_link) # Insert layer toc_root = QgsProject.instance().layerTreeRoot() selected_node = iface.layerTreeView().currentNode() if selected_node.nodeType() == selected_node.NodeGroup: toc_root = selected_node if ds.type.lower() in (KNOWN_DRIVERS.WMS.lower(), KNOWN_DRIVERS.TMS.lower()): position = len(toc_root.children()) # Insert to bottom if wms\tms else: position = 0 # insert to top addMapLayer(layer, False) toc_root.insertLayer(position, layer) # Save link service_layers.append(layer) # Set OTF CRS Transform for map if PluginSettings.enable_otf_3857() and ds.type == KNOWN_DRIVERS.TMS: if hasattr(iface.mapCanvas(), "setCrsTransformEnabled"): # Need for QGIS2. In QGIS3 CRS transformation is always enabled iface.mapCanvas().setCrsTransformEnabled(True) iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)