def apply_style(layer, style_name, stype="tools"): qml_path = STYLES_ROOT / stype / style_name style_manager = layer.styleManager() style_manager.reset() style = QgsMapLayerStyle() style.readFromLayer(layer) current_style_name = layer.styleManager().currentStyle() # default style name depends on language settings for qml_file in qml_path.glob("*.qml"): style_name = qml_file.stem.capitalize() style_manager.addStyle(style_name, style) style_manager.setCurrentStyle(style_name) (message, success) = layer.loadNamedStyle(os.path.join(qml_path, qml_file)) if not success: # if style not loaded remove it style_manager.removeStyle(style_name) logger.info("Styling file not succesfully loaded: {fn}".format(fn=qml_file)) logger.info(message) layer.styleManager().setCurrentStyle('Default') layer.styleManager().removeStyle(current_style_name) return
def add_style(name, params, project, project_path, qgis_layer, request): """Add a style to a layer in a QGIS project.""" maplayer_registry = QgsMapLayerRegistry.instance() # QML qml_path = params.get('QML') if not qml_path: request.appendBody('QML parameter is missing.\n') return if not exists(qml_path): request.appendBody('QML path does not exist.\n') return # REMOVE QML remove_qml = params.get('REMOVEQML') if remove_qml: if remove_qml.upper() in ['1', 'YES', 'TRUE']: remove_qml = True else: remove_qml = False else: remove_qml = False style_manager = qgis_layer.styleManager() if name in style_manager.styles(): request.appendBody('NAME is already an existing style.\n') return # Let's process the QML with open(qml_path, 'r') as qml_file: data = qml_file.read() style = QgsMapLayerStyle(data) if not style.isValid(): request.appendBody('The QML is not valid.\n') return result = style_manager.addStyle(name, style) if not result: request.appendBody('Error while adding the style.\n') return project.write() project.clear() # The project has been overridden. We need to regenerate the legend # manually. qgis_layers = [ layer for layer in maplayer_registry.mapLayers().itervalues()] generate_legend(qgis_layers, project_path) if remove_qml: QgsMessageLog.logMessage( 'Removing QML {path}'.format(path=qml_path)) remove(qml_path) request.appendBody('OK') return True
def addQWeatherLayer(self): # load qml to current style self.QWeather = self.iface.addVectorLayer(self.outQWeatherGeoJson, self.layerTemp, "ogr") style_manager = self.QWeather.styleManager() # read valid style from layer style = QgsMapLayerStyle() style.readFromLayer(self.QWeather) self.QWeather.loadNamedStyle( os.path.join(self.plugin_dir, "icons", self.style2 + ".qml")) style_manager.renameStyle("default", "direction") style_name = "humidity" # add style with new name style_manager.addStyle(style_name, style) # set new style as current style_manager.setCurrentStyle(style_name) self.QWeather.loadNamedStyle( os.path.join(self.plugin_dir, "icons", "humidity.qml")) style_manager.renameStyle(style_name, style_name) style = QgsMapLayerStyle() style.readFromLayer(self.QWeather) style_name = self.style # add style with new name style_manager.addStyle(style_name, style) # set new style as current style_manager.setCurrentStyle(style_name) self.QWeather.loadNamedStyle( os.path.join(self.plugin_dir, "icons", self.style + ".qml")) style_manager.renameStyle(self.style, "temperature")
def replace_style(self, style, qml): """Replaces the style QML :param style: name of the style to replace :type style: str :param qml: :type qml: str :return: True on success :rtype: bool """ result = False with QgisProjectFileLocker(self.project) as project: layer = self.qgis_layer if layer is None: return False sm = layer.styleManager() # Validate! doc = QDomDocument('qgis') if not doc.setContent(qml)[0]: return False tmp_layer = layer.clone() if not tmp_layer.importNamedStyle(doc)[0]: return False del (tmp_layer) # If the style is current, just replace it in the layer if sm.currentStyle() == style: return layer.importNamedStyle(doc)[0] else: new_style = QgsMapLayerStyle(qml) result = sm.addStyle(style, new_style) result = sm.removeStyle(style) and sm.addStyle( style, new_style) if result: assert self.style(style).xmlData() == new_style.xmlData() result = result and project.update_qgis_project() return result
def style(self, name): """Returns the style from name :param style: name of the style to return :type style: str :return: The requested style :rtype: QgsMapLayerStyle """ layer = self.qgis_layer if layer is None: return QgsMapLayerStyle() sm = layer.styleManager() return sm.style(name)
def add_style(self, style, qml): """Deletes a style :param style: name of the new style :type style: str :param qml: :type qml: str :return: True on success :rtype: bool """ layer = self.qgis_layer if layer is None: return False result = False with QgisProjectFileLocker(self.project) as project: sm = layer.styleManager() if sm.currentStyle() == style: return False # Validate! doc = QDomDocument('qgis') if not doc.setContent(qml)[0]: return False tmp_layer = layer.clone() if not tmp_layer.importNamedStyle(doc)[0]: return False del (tmp_layer) new_style = QgsMapLayerStyle(qml) result = sm.addStyle(style, new_style) if result: result = result and project.update_qgis_project() return result
def _qml_of(self, layer: QgsMapLayer) -> str: ls = QgsMapLayerStyle() ls.readFromLayer(layer) return ls.xmlData()
def processAlgorithm(self, parameters, context, feedback): ''' Here is where the processing itself takes place. ''' # if not is_dependencies_satisfied: return {} tmpf = str(uuid.uuid4()) res_file = os.path.join(self._tmpDir, tmpf + '.htm') self._error = '' the_layer = self.parameterAsLayer(parameters, self.THE_LAYER, context) is_save = self.parameterAsBool(parameters, self.IS_SAVE, context) is_force = self.parameterAsBool(parameters, self.IS_FORCE, context) qml_path = self.parameterAsFile(parameters, self.QML_DIR, context) if qml_path == '' or self._tmpDir in qml_path: qml_path = os.path.split(the_layer.source())[0] if not os.path.exists(qml_path): qml_path = self._tmpDir output_file = self.parameterAsFileOutput(parameters, self.OUTPUT, context) if (self._default_output in output_file) or (output_file == ''): output_file = res_file else: output_file = os.path.splitext(output_file)[0] + '.htm' style_manager = the_layer.styleManager() lname = the_layer.name() # read valid style from layer style = QgsMapLayerStyle() style.readFromLayer(the_layer) c_style = style_manager.currentStyle() if is_save: # Save to files self._results = '<strong>%s</strong><br/>\n' % self._the_strings['SAVE'] for style_name in style_manager.styles(): style_manager.setCurrentStyle(style_name) the_qml = os.path.join(qml_path, the_layer.name()+'_'+style_name+".qml") _, flg = the_layer.saveNamedStyle(the_qml) if flg: self._results+='%s: %s<br/>\n' % (style_name, self._the_strings['O1']) else: self._results+='%s: %s<br/>\n' % (style_name, self._the_strings['N1']) # else: # Load from files - format should be: LayerName_StyleName.qml # Adapted from answer at: https://gis.stackexchange.com/questions/288341 self._results = '<strong>%s</strong><br/>\n' % self._the_strings['LOAD'] # for qml_file in [f for f in os.listdir(qml_path) if os.path.isfile(os.path.join(qml_path, f)) and f.endswith('.qml') and (is_force or (not is_force and lname.lower() in os.path.splitext(f)[0].lower()))]: # get style name from filename if not is_force: # style name from sidecar bare = os.path.splitext(qml_file)[0] if bare.lower() != lname.lower(): bare = bare.replace(lname, '') else: bare = '_default' style_name = bare[1:] else: # style name from generic qml style_name = os.path.splitext(qml_file)[0] # style_manager.addStyle(style_name, style) style_manager.setCurrentStyle(style_name) _, b = the_layer.loadNamedStyle(os.path.join(qml_path, qml_file)) if not b: style_manager.removeStyle(style_name) self._results+='%s: %s<br/>\n' % (style_name, self._the_strings['N2']) else: self._results+='%s: %s<br/>\n' % (style_name, self._the_strings['O2']) style_manager.setCurrentStyle(c_style) fil = self._create_HTML(qml_path, the_layer.source(), output_file) # return {self.OUTPUT:fil}