def object_to_qlr( obj, input_file, output_path, context: Context, use_relative_paths: bool = False) -> Tuple[bool, Optional[str]]: """ Converts an ESRI object to QLR """ root_node, _ = LayerConverter.object_to_layers_and_tree( obj, input_file, context) output_path = QgsFileUtils.ensureFileNameHasExtension( output_path, ['qlr']) file = QFile(output_path) if not file.open(QFile.WriteOnly | QFile.Truncate): return False, file.errorString() rw_context = QgsReadWriteContext() if not use_relative_paths: rw_context.setPathResolver(QgsPathResolver()) else: rw_context.setPathResolver(QgsPathResolver(output_path)) doc = QDomDocument("qgis-layer-definition") res, error = QgsLayerDefinition.exportLayerDefinition( doc, root_node.children(), rw_context) if res: stream = QTextStream(file) doc.save(stream, 2) return True, None return res, error
def _change_data_source(self, layer, datasource, provider_key): """Due to the fact that a project r/w context is not available inside the map layers classes, the original style and subset string restore happens in app, this function replicates app behavior""" options = QgsDataProvider.ProviderOptions() subset_string = '' if not layer.isValid(): try: subset_string = layer.dataProvider().subsetString() except: pass layer.setDataSource(datasource, layer.name(), provider_key, options) if subset_string: layer.setSubsetString(subset_string) self.assertTrue(layer.originalXmlProperties(), layer.name()) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) errorMsg = '' doc = QDomDocument() self.assertTrue(doc.setContent(layer.originalXmlProperties())) layer_node = QDomNode(doc.firstChild()) self.assertTrue(layer.readSymbology(layer_node, errorMsg, context))
def xml_to_layer_style(self,qgis_layer,xml): ''' retrieve qgis style from the setting sheet :param qgis_layer: :return: ''' XMLDocument = QDomDocument() error = None XMLDocument.setContent(xml) XMLStyleNode = XMLDocument.namedItem("style") rw_context = QgsReadWriteContext() rw_context.setPathResolver( QgsProject.instance().pathResolver() ) qgis_layer.readSymbology(XMLStyleNode, error, rw_context)
def layer_style_to_xml(self,qgis_layer): ''' saves qgis style to the setting sheet :param qgis_layer: :return: ''' XMLDocument = QDomDocument("qgis_style") XMLStyleNode = XMLDocument.createElement("style") XMLDocument.appendChild(XMLStyleNode) error = None rw_context = QgsReadWriteContext() rw_context.setPathResolver( QgsProject.instance().pathResolver() ) qgis_layer.writeSymbology(XMLStyleNode, XMLDocument, error,rw_context) xmldoc = XMLDocument.toString(1) return xmldoc
def create_qgis_template_output(output_path, layout): """Produce QGIS Template output. :param output_path: The output path. :type output_path: str :param composition: QGIS Composition object to get template. values :type composition: qgis.core.QgsLayout :return: Generated output path. :rtype: str """ # make sure directory is created dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) layout.saveAsTemplate(output_path, context) return output_path
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != 'qgis_style': return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement('symbols') symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == 'symbol': symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ 'name': symbol_element.attribute('name'), 'symbol': symbol }) symbol_element = symbol_element.nextSiblingElement() return True
def __init__(self, id, gtotool, config, debug): super(run, self).__init__() try: self.debug = debug self.gtotool=gtotool self.gtomain = gtotool.gtomain self.info =gtotool.info self.metadata = self.gtomain.metadata templatedir = self.metadata.dirPrintLayouts self.iface = self.gtomain.iface #tool data template = config.get('template',None) activetool= config.get('active_tool',None) scale = config.get('scale',0) #init templatefile = None layoutname =config.get('layoutname', None) if template and layoutname is None: layoutname= os.path.splitext(template)[0]#default layoutname for template if self.debug:self.info.log("layoutname:",layoutname) prj = QgsProject.instance() projectLayoutManager = prj.layoutManager()#QgsLayoutManager self.layout = None if template is not None: templatefile = os.path.join(templatedir , template) if debug: self.info.log("template:",templatefile) if os.path.isfile(templatefile): f= open(templatefile, 'r') templateContent = f.read() f.close() doc=QDomDocument() doc.setContent(templateContent) pr = QgsPathResolver(templatefile) rwc = QgsReadWriteContext() rwc.setPathResolver(pr) self.layout = QgsPrintLayout(prj) self.layout.loadFromTemplate(doc,rwc) self.layout.setName(layoutname) projectLayoutManager.addLayout(self.layout) self.layout = projectLayoutManager.layoutByName(layoutname) if self.debug: self.info.log(type(self.layout)) if self.debug and self.layout:self.info.log("found layout:",self.layout.name()) if self.layout: result = self.iface.openLayoutDesigner(self.layout)#QgsLayoutDesignerInterface self.layoutview = result.view()#QgsLayoutView currenttool = self.layoutview.tool()#QgsLayoutViewTool if self.debug: self.info.log(currenttool.toolName()) if activetool: tool = QgsLayoutViewToolMoveItemContent(self.layoutview) self.layoutview.setTool(tool) #itemMap = QgsLayoutItemMap(self.layout) referencemap = self.layout.referenceMap() referencemap.zoomToExtent(self.iface.mapCanvas().extent()) if scale < 0: referencemap.setScale(self.iface.mapCanvas().scale()) elif scale > 0: referencemap.setScale(scale) referencemap.refresh() if activetool: menu = result.editMenu() for a in menu.actions(): if a.objectName() == activetool: if self.debug: self.info.log("set active tool:",activetool) a.trigger() break self.result = True else: self.result="Layout <%s> not found!" % layoutname except Exception as e: self.info.err(e)
def run(self): project = QgsProject.instance() # set qml scangisLayer = self.iface.activeLayer() #print(scangisLayer.name()) scangisLayer.loadNamedStyle(self.scangisStyle) # delete existing deelnemers virtual layer oldLayers = project.mapLayersByName(self.virtualLayerName) for oldLayer in oldLayers: project.removeMapLayer(oldLayer.id()) # create new virtual layer query = u'?query=SELECT min(ID) AS ID, DEELN_NAAM, st_union(geometry) AS geometry FROM "{}" GROUP BY DEELN_NAAM'.format( scangisLayer.name()) virtualLayer = QgsVectorLayer(query, self.virtualLayerName, "virtual") project.addMapLayer(virtualLayer) ltr = QgsProject.instance().layerTreeRoot() rootLayer = ltr.findLayer(virtualLayer.id()) rootLayer.setItemVisibilityChecked(False) self.iface.mapCanvas().refreshAllLayers() # delete existing atlas layout layoutManager = project.layoutManager() #print(layoutManager) #print(layoutManager.layouts()) oldLayout = layoutManager.layoutByName(self.layoutName) if oldLayout is not None: layoutManager.removeLayout(oldLayout) # create new layout self.atlasLayout = QgsPrintLayout(project) # load layout template fl = QFile(self.templateFile) doc = QDomDocument() doc.setContent(fl) rw_context = QgsReadWriteContext() rw_context.setPathResolver(project.pathResolver()) self.atlasLayout.loadFromTemplate(doc, rw_context) # set name self.atlasLayout.setName(self.layoutName) # add to project layoutManager.addLayout(self.atlasLayout) # turn on atlas atl = self.atlasLayout.atlas() atl.setEnabled(True) atl.setCoverageLayer(virtualLayer) atl.setHideCoverage(True) itemId = u'map1' item = self.getLayoutItem(itemId, QgsLayoutItemMap) item.setAtlasDriven(True) # set title itemId = u'label_title' item = self.getLayoutItem(itemId, QgsLayoutItemLabel) #item.setText(u'[% attribute(@atlas_feature, \'DEELN_NAAM\') %]') item.setText(u'[% "DEELN_NAAM" %]') # set source info itemId = u'label_source' item = self.getLayoutItem(itemId, QgsLayoutItemLabel) exp = u"[% format_date(now(), 'dd-MM-yyyy (hh:mm:ss)') || '\\n' || 'pagina ' || @atlas_featurenumber || '/' || @atlas_totalfeatures %]" item.setText(exp) item.setHAlign(2) # right item.setVAlign(64) # bottom # set legend filter itemId = u'legend1' item = self.getLayoutItem(itemId, QgsLayoutItemLegend) #print(item) item.setLegendFilterByMapEnabled(True) #QMessageBox.information(None, u'Scangis Atlas', u'Atlas finished! :)') designer = self.iface.openLayoutDesigner(self.atlasLayout) # new in qgis 3.3 if qgis.utils.Qgis.QGIS_VERSION_INT >= 30300: designer.setAtlasPreviewEnabled(True)
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != "qgis_style": return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement("symbols") symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == "symbol": symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ "name": symbol_element.attribute("name"), "symbol": symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement("colorramps") ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == "colorramp": colorramp = QgsSymbolLayerUtils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ "name": ramp_element.attribute("name"), "colorramp": colorramp }) ramp_element = ramp_element.nextSiblingElement() # Get all the TextFormats - textformats - textformat self._textformats = [] textformats_element = document_element.firstChildElement("textformats") textformat_element = textformats_element.firstChildElement() while not textformat_element.isNull(): if textformat_element.tagName() == "textformat": textformat = QgsTextFormat() textformat.readXml(textformat_element, QgsReadWriteContext()) if textformat: self._textformats.append({ "name": textformat_element.attribute("name"), "textformat": textformat, }) textformat_element = textformat_element.nextSiblingElement() # Get all the LabelSettings - labelsettings - labelsetting - # QgsPalLayerSettings.readXML? self._labelsettings = [] labels_element = document_element.firstChildElement("labelsettings") label_element = labels_element.firstChildElement() while not label_element.isNull(): if label_element.tagName() == "labelsetting": labelsettings = QgsPalLayerSettings() labelsettings.readXml(label_element, QgsReadWriteContext()) if labelsettings: self._labelsettings.append({ "name": label_element.attribute("name"), "labelsettings": labelsettings, }) label_element = label_element.nextSiblingElement() return True