def testSymbolSizeAfterReload(self): # create a layer layer = createLayerWithOnePoint() # load a sld with marker size sld = 'symbol_layer/QgsSvgMarkerSymbolLayer.sld' mFilePath = os.path.join(TEST_DATA_DIR, sld) layer.loadSldStyle(mFilePath) # get the size and unit of the symbol sl = layer.renderer().symbol().symbolLayers()[0] first_size = sl.size() first_unit = sl.outputUnit() # in pixels # export sld into a qdomdocument with namespace processing activated doc = QDomDocument() msg = "" layer.exportSldStyle(doc, msg) doc.setContent(doc.toString(), True) self.assertTrue(msg == "") # reload the same sld root = doc.firstChildElement("StyledLayerDescriptor") el = root.firstChildElement("NamedLayer") layer.readSld(el, msg) # extract the size and unit of symbol sl = layer.renderer().symbol().symbolLayers()[0] second_size = sl.size() second_unit = sl.outputUnit() # size and unit should be the same after export and reload the same # sld description self.assertEqual(first_size, second_size) self.assertEqual(first_unit, second_unit)
def on_btnSave_clicked(self): fileName, _ = QFileDialog.getSaveFileName( None, self.tr("Export Colors and elevations as XML"), QDir.homePath(), self.tr("XML files (*.xml *.XML)") ) if fileName == "": return if not fileName.lower().endswith(".xml"): fileName += ".xml" doc = QDomDocument() colorsElem = doc.createElement("ReliefColors") doc.appendChild(colorsElem) colors = self.reliefColors() for c in colors: elem = doc.createElement("ReliefColor") elem.setAttribute("MinElevation", str(c.minElevation)) elem.setAttribute("MaxElevation", str(c.maxElevation)) elem.setAttribute("red", str(c.color.red())) elem.setAttribute("green", str(c.color.green())) elem.setAttribute("blue", str(c.color.blue())) colorsElem.appendChild(elem) with codecs.open(fileName, "w", encoding="utf-8") as f: f.write(doc.toString(2))
def on_btnSave_clicked(self): fileName, _ = QFileDialog.getSaveFileName(None, self.tr('Export Colors and elevations as XML'), QDir.homePath(), self.tr('XML files (*.xml *.XML)')) if fileName == '': return if not fileName.lower().endswith('.xml'): fileName += '.xml' doc = QDomDocument() colorsElem = doc.createElement('ReliefColors') doc.appendChild(colorsElem) colors = self.reliefColors() for c in colors: elem = doc.createElement('ReliefColor') elem.setAttribute('MinElevation', str(c.minElevation)) elem.setAttribute('MaxElevation', str(c.maxElevation)) elem.setAttribute('red', str(c.color.red())) elem.setAttribute('green', str(c.color.green())) elem.setAttribute('blue', str(c.color.blue())) colorsElem.appendChild(elem) with codecs.open(fileName, 'w', encoding='utf-8') as f: f.write(doc.toString(2))
def createSimpleMemorial(self): tempDoc = QDomDocument() simple = QFile(self.simpleMemorial) simple.open(QIODevice.ReadOnly) loaded = tempDoc.setContent(simple) simple.close() element = tempDoc.documentElement() nodes = element.elementsByTagName("table") table = nodes.item(0).toElement() tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0)) table.appendChild(tr) convergence = float(self.convergenciaEdit.text()) rowCount = self.tableWidget.rowCount() for i in range(0,rowCount): lineElement = tempDoc.createElement("tr") lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,0).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,1).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,2).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,3).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,4).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,5).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,6).text(), 0, 0)) table.appendChild(lineElement) simple = open(self.simpleMemorial, "w", encoding='utf-8') simple.write(tempDoc.toString()) simple.close()
def testClone(self): myPath = os.path.join(unitTestDataPath('raster'), 'band1_float32_noct_epsg4326.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() layer = QgsRasterLayer(myPath, myBaseName) renderer = layer.renderer().clone() renderer.setOpacity(33.3) layer.setRenderer(renderer) # clone layer clone = layer.clone() # generate xml from layer layer_doc = QDomDocument("doc") layer_elem = layer_doc.createElement("maplayer") layer.writeLayerXml(layer_elem, layer_doc, QgsReadWriteContext()) # generate xml from clone clone_doc = QDomDocument("doc") clone_elem = clone_doc.createElement("maplayer") clone.writeLayerXml(clone_elem, clone_doc, QgsReadWriteContext()) # replace id within xml of clone clone_id_elem = clone_elem.firstChildElement("id") clone_id_elem_patch = clone_doc.createElement("id") clone_id_elem_patch_value = clone_doc.createTextNode(layer.id()) clone_id_elem_patch.appendChild(clone_id_elem_patch_value) clone_elem.replaceChild(clone_id_elem_patch, clone_id_elem) # update doc clone_doc.appendChild(clone_elem) layer_doc.appendChild(layer_elem) # compare xml documents self.assertEqual(layer_doc.toString(), clone_doc.toString())
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 write_to_file(self, file_name: str) -> bool: """ Writes the settings to an XML file """ document = QDomDocument("dataplotly") elem = self.write_xml(document) document.appendChild(elem) try: with open(file_name, "w") as f: f.write('<?xml version="1.0" encoding="UTF-8"?>\n') f.write(document.toString()) return True except FileNotFoundError: return False
def mimeUri(self): # pylint: disable=missing-docstring if not self.bookmark: u = QgsMimeDataUtils.Uri() u.layerType = "custom" u.providerKey = "esri_dat" u.name = self.name() u.uri = self.path() return u else: u = QgsMimeDataUtils.Uri() u.layerType = "custom" u.providerKey = "bookmark" u.name = self.name() doc = QDomDocument() doc.appendChild(self.bookmark.writeXml(doc)) u.uri = doc.toString() return u
def testLoadWriteRenderingScaleVisibility(self): """Test write and load scale visibility, see GH #33840""" vl = QgsVectorLayer("LineString?crs=epsg:4326", "result", "memory") vl.setScaleBasedVisibility(True) vl.setMinimumScale(125.0) vl.setMaximumScale(1.25) style = QDomDocument() style.setContent("<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'><qgis></qgis>") node = style.firstChild() self.assertTrue(vl.writeStyle(node, style, "Error writing style", QgsReadWriteContext(), QgsMapLayer.Rendering)) style_content = style.toString() del(vl) # Read vl2 = QgsVectorLayer("LineString?crs=epsg:4326", "result", "memory") self.assertFalse(vl2.hasScaleBasedVisibility()) style2 = QDomDocument() style2.setContent(style_content) self.assertTrue(vl2.readStyle(style.namedItem('qgis'), "Error reading style", QgsReadWriteContext(), QgsMapLayer.Rendering)) self.assertTrue(vl2.hasScaleBasedVisibility()) self.assertEqual(vl2.minimumScale(), 125.0) self.assertEqual(vl2.maximumScale(), 1.25)
def createSimpleMemorial(self): tempDoc = QDomDocument() simple = QFile(self.simpleMemorial) simple.open(QIODevice.ReadOnly) loaded = tempDoc.setContent(simple) simple.close() element = tempDoc.documentElement() nodes = element.elementsByTagName("table") table = nodes.item(0).toElement() tr = tempDoc.createElement("tr") tr.appendChild( self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0)) table.appendChild(tr) convergence = float(self.convergenciaEdit.text()) rowCount = self.tableWidget.rowCount() for i in range(0, rowCount): lineElement = tempDoc.createElement("tr") lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 0).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 1).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 2).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 3).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 4).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 5).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 6).text(), 0, 0)) table.appendChild(lineElement) simple = open(self.simpleMemorial, "w", encoding='utf-8') simple.write(tempDoc.toString()) simple.close()
def saveStyleFromQgisLayer(layer, server, user, repo): doc = QDomDocument() layer.exportNamedStyle(doc, categories=QgsMapLayer.Symbology | QgsMapLayer.Labeling) server.addStyle(user, repo, layer.name(), doc.toString())
def processAlgorithm(self, parameters, context, feedback): output = {self.OUTPUT_STATUS: 0, self.OUTPUT_STRING: ''} # Parameters connection_name_central = parameters[self.CONNECTION_NAME_CENTRAL] # store parameters ls = lizsyncConfig() ls.setVariable('postgresql:central/name', connection_name_central) ls.save() # Get current project file project = context.project() input_path = project.absoluteFilePath() output_path = input_path.replace('.qgs', '_mobile.qgs') output_directory = project.baseName() + '_mobile/' # Save to new file feedback.pushInfo(tr('Save mobile project')) if os.path.isfile(output_path): os.remove(output_path) try: shutil.copy(input_path, output_path) except IOError as e: msg = tr('Unable to copy the current project file') msg += ' ' + e raise QgsProcessingException(msg) except Exception as e: msg = tr('Unexpected error') + ' ' + sys.exc_info() msg += ' ' + e raise QgsProcessingException(msg) feedback.pushInfo(tr('* Mobile project saved')) feedback.pushInfo('') # Read mobile project file as XML feedback.pushInfo(tr('Read XML from saved project')) content = None with open(input_path, 'r') as f: content = f.read() dom = QDomDocument() dom.setContent(content) feedback.pushInfo(tr('* XML successfully read')) feedback.pushInfo('') # Get layers and layers id pg_layers = self.parameterAsLayerList(parameters, self.PG_LAYERS, context) pg_layers = [ layer for layer in pg_layers if layer.providerType() == 'postgres' ] pg_ids = [layer.id() for layer in pg_layers] pg_changed = [] gpkg_layers = self.parameterAsLayerList(parameters, self.GPKG_LAYERS, context) gpkg_ids = [layer.id() for layer in gpkg_layers] gpkg_changed = [] # Loop for each layer and change datasource if needed feedback.pushInfo( tr('Change the datasource of layers to make the QGIS project portable' )) nodelist = dom.elementsByTagName('maplayer') for node in (nodelist.at(i) for i in range(nodelist.count())): # Get layer id, name, datasource and provider layerid = node.firstChildElement('id').text() layername = node.firstChildElement('layername').text() datasource = node.firstChildElement('datasource').text() # PostgreSQL if layerid in pg_ids: # Replace datasource by field localhost datasource new_source, msg = self.replacePostgresqlDatasource( connection_name_central, datasource, layername) if not new_source: raise QgsProcessingException(msg) if new_source != datasource: node.firstChildElement( 'datasource').firstChild().setNodeValue(new_source) # Add to the list pg_changed.append(layername) # GeoPackage # We do not change the datasource for PostgreSQL layers chosen for editing # To avoid misconfiguration if layerid in gpkg_ids and layerid not in pg_ids: # Replace datasource with the geopackage file path and layer name new_source = './{}/layers.gpkg|layername={}'.format( output_directory, layername) node.firstChildElement('datasource').firstChild().setNodeValue( new_source) # We must also change the provider into ogr node.firstChildElement('provider').firstChild().setNodeValue( 'ogr') # Add to the list gpkg_changed.append(layername) feedback.pushInfo('') # Write XML content back if pg_changed or gpkg_changed: # Convert XML to string content = dom.toString() # Log changed layers feedback.pushInfo( tr('PostgreSQL layers to edit in the field') + ':') for layer in pg_changed: feedback.pushInfo('* {}'.format(layer)) feedback.pushInfo('') feedback.pushInfo(tr('Other layers converted to GeoPackage') + ':') for layer in gpkg_changed: feedback.pushInfo('* {}'.format(layer)) # Write file with open(output_path, 'w') as f: f.write(content) feedback.pushInfo('') if not pg_changed: msg = tr( 'No PostgreSQL layers datasource could be changed to target the clone database' ) raise QgsProcessingException(msg) # Log msg = tr( 'The current QGIS project mobile version has been successfully saved. Please send it to your field device.' ) feedback.pushInfo(msg) feedback.pushInfo(output_path) output = {self.OUTPUT_STATUS: 1, self.OUTPUT_STRING: msg} return output
def createAndParseSld(qgisLayerItem): document = QDomDocument() header = document.createProcessingInstruction( 'xml', 'version=\'1.0\' encoding=\'UTF-8\'') document.appendChild(header) root = document.createElementNS('http://www.opengis.net/sld', 'StyledLayerDescriptor') root.setAttribute('version', '1.0.0') root.setAttribute('xmlns:ogc', 'http://www.opengis.net/ogc') root.setAttribute('xmlns:sld', 'http://www.opengis.net/sld') root.setAttribute('xmlns:gml', 'http://www.opengis.net/gml') document.appendChild(root) namedLayerNode = document.createElement('sld:NamedLayer') root.appendChild(namedLayerNode) qgisLayerItem.layer.writeSld(namedLayerNode, document, '') nameNode = namedLayerNode.firstChildElement('se:Name') oldNameText = nameNode.firstChild() newname = qgisLayerItem.parentShogunLayer.source['layerNames'] newNameText = document.createTextNode(newname) nameNode.appendChild(newNameText) nameNode.removeChild(oldNameText) userStyleNode = namedLayerNode.firstChildElement('UserStyle') userStyleNameNode = userStyleNode.firstChildElement('se:Name') userStyleNameText = userStyleNameNode.firstChild() userStyleNameNode.removeChild(userStyleNameText) userStyleNameNode.appendChild( document.createTextNode(qgisLayerItem.stylename)) titleNode = document.createElement('sld:Title') title = document.createTextNode('A QGIS-Style for ' + qgisLayerItem.layer.name()) titleNode.appendChild(title) userStyleNode.appendChild(titleNode) defaultNode = document.createElement('sld:IsDefault') defaultNode.appendChild(document.createTextNode('1')) userStyleNode.appendChild(defaultNode) featureTypeStyleNode = userStyleNode.firstChildElement( 'se:FeatureTypeStyle') featureTypeStyleNameNode = document.createElement('sld:Name') featureTypeStyleNameNode.appendChild(document.createTextNode('name')) featureTypeStyleNode.appendChild(featureTypeStyleNameNode) rules = featureTypeStyleNode.elementsByTagName('se:Rule') for x in range(rules.length()): rule = rules.at(x) rule.removeChild(rule.firstChildElement('se:Description')) # Check if custom icons are used in symbology and replace the text: # search if tag 'se:OnlineResource' is in the sld document listOfGraphics = rule.toElement().elementsByTagName('se:OnlineResource') if not listOfGraphics.isEmpty(): for x in range(listOfGraphics.length()): graphicNode = listOfGraphics.at(x) currentIcon = graphicNode.attributes().namedItem( 'xlink:href').nodeValue() iconUrl = qgisLayerItem.ressource.prepareIconForUpload(currentIcon) graphicNode.toElement().setAttribute('xlink:href', iconUrl) graphicNode.toElement().setAttribute( 'xmlns:xlink', 'http://www.w3.org/1999/xlink') sld = document.toString() # in qgis3 layer.writeSld() also incluedes labeling in the output sld, # whereas in qgis2 we have to do this manually by using this module's function # getLabelingAsSld ## TODO: The automatic sld labeling from QGIS 3 produces an extra rule for # every labeling style, thus leading to a less beautiful viewe in the # shogun2-webapp styler - is this a problem? if qgisLayerItem.layer.labelsEnabled() and PYTHON_VERSION < 3: labelSld = getLabelingAsSld(qgisLayerItem.layer) sld = sld.replace('</se:Rule>', labelSld + '</se:Rule>') sld = sld.replace('ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"', 'ogc:Filter') # the following fixes weird problems with the sld compability with the # shogun webapp sld = sld.replace('<ogc:And>', '') sld = sld.replace('</ogc:And>', '') sld = sld.replace('<se:Name> ', '<se:Name>') sld = sld.replace(' </se:Name>', '</se:Name>') sld = sld.replace('StyledLayerDescriptor', 'sld:StyledLayerDescriptor') sld = sld.replace('UserStyle', 'sld:UserStyle') sld = sld.replace('se:', 'sld:') sld = sld.replace('SvgParameter', 'CssParameter') sld = sld.replace('\n', '') sld = sld.replace('\t', '') return sld
def addToDefaultProject(maps, visibleMaps, authcfg=None): """Add basemaps to the existing default project""" layers = [] for m in maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], 'wms') # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if os.path.isfile(defaultProjectPath()): backup = defaultProjectPath().replace( '.qgs', '-%s.qgs' % datetime.now().strftime('%Y-%m-%d-%H_%M_%S')) shutil.copy2(defaultProjectPath(), backup) # open default project with open(defaultProjectPath()) as f: content = f.read() doc = QDomDocument() setOk, errorString, errorLine, errorColumn = doc.setContent(content) if not setOk: return False root = doc.documentElement() for layer in layers: is_visible = layer.name() in visibleMaps xml = QgsMapLayer.asLayerDefinition([layer]) r = xml.documentElement() mapLayerElement = r.firstChildElement("maplayers").firstChildElement("maplayer") layerTreeLayerElement = doc.createElement("layer-tree-layer") layerTreeLayerElement.setAttribute("expanded", "1") layerTreeLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") layerTreeLayerElement.setAttribute("id", layer.id()) layerTreeLayerElement.setAttribute("name", layer.name()) customPropertiesElement = doc.createElement("customproperties") layerTreeLayerElement.appendChild(customPropertiesElement) legendLayerElement = doc.createElement("legendlayer") legendLayerElement.setAttribute("drawingOrder", "-1") legendLayerElement.setAttribute("open", "true") legendLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") legendLayerElement.setAttribute("name", layer.name()) legendLayerElement.setAttribute("showFeatureCount", "0") filegroupElement = doc.createElement("filegroup") filegroupElement.setAttribute("open", "true") filegroupElement.setAttribute("hidden", "false") legendlayerfileElement = doc.createElement("legendlayerfile") legendlayerfileElement.setAttribute("isInOverview", "0") legendlayerfileElement.setAttribute("layerid", layer.id()) legendlayerfileElement.setAttribute("visible", "1" if is_visible else "0") filegroupElement.appendChild(legendlayerfileElement) legendLayerElement.appendChild(filegroupElement) crsElement = doc.createElement("layer_coordinate_transform") crsElement.setAttribute("destAuthId", "EPSG:3857") crsElement.setAttribute("srcAuthId", "EPSG:3857") crsElement.setAttribute("srcDatumTransform", "-1") crsElement.setAttribute("destDatumTransform", "-1") crsElement.setAttribute("layerid", layer.id()) itemElement = doc.createElement("item") text = doc.createTextNode(layer.id()) itemElement.appendChild(text) e = root.firstChildElement("layer-tree-group") e.appendChild(layerTreeLayerElement) e = root.firstChildElement("mapcanvas").firstChildElement("layer_coordinate_transform_info") e.appendChild(crsElement) e = root.firstChildElement("layer-tree-canvas").firstChildElement("custom-order") e.appendChild(itemElement) e = root.firstChildElement("legend") e.appendChild(legendLayerElement) e = root.firstChildElement("projectlayers") e.appendChild(mapLayerElement) with open(defaultProjectPath(), "wb+") as f: f.write(doc.toString(2)) settings = QSettings() settings.setValue('/qgis/newProjectDefault', True) return True
class UiInspector: def __init__(self): self.ui_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '../src/ui/*.ui')) self.printMsg("Loading UI files " + self.ui_dir) # list of widget classes we want to follow self.follow = [ QWidget, QDialog, QCheckBox, QComboBox, QDial, QPushButton, QLabel, QLCDNumber, QLineEdit, QRadioButton, QScrollBar, QSlider, QSpinBox, QTextEdit, QDateEdit, QTimeEdit, QDateTimeEdit, QListView, QProgressBar, QTableView, QTabWidget, QTextBrowser, QDialogButtonBox, QScrollArea, QGroupBox, QStackedWidget, ] def printMsg(self, msg): sys.stderr.write(msg + "\n") def widgetXml(self, element, widget, level=0, label=None): # print tostring ( element ) # self.printMsg ( "class: " + str( type ( widget ) ) ) # self.printMsg ( "objectName: " + widget.objectName() ) # self.printMsg ( "windowTitle: " + widget.windowTitle() ) if not widget.objectName(): return lab = label if hasattr(widget, 'text'): lab = widget.text() if widget.windowTitle(): label = widget.windowTitle() if not lab: lab = '' subElement = self.doc.createElement('widget') subElement.setAttribute('class', widget.__class__.__name__) subElement.setAttribute('objectName', widget.objectName()) subElement.setAttribute('label', lab) element.appendChild(subElement) # print str ( widget.children () ) # tab widget label is stored in QTabWidget->QTabBarPrivate->tabList->QTab .. if type(widget) in [QTabWidget]: children = list({ 'widget': widget.widget(i), 'label': widget.tabText(i) } for i in range(0, widget.count())) else: children = list({ 'widget': c, 'label': None } for c in widget.children()) for child in children: w = child['widget'] if w.isWidgetType() and (type(w) in self.follow): self.widgetXml(subElement, w, level + 1, child['label']) def xml(self): self.doc = QDomDocument() element = self.doc.createElement("qgiswidgets") self.doc.appendChild(element) for p in glob.glob(self.ui_dir): self.printMsg("Loading " + p) # qgsrasterlayerpropertiesbase.ui is giving: No module named qwt_plot try: widget = loadUi(p) # print dir ( ui ) self.widgetXml(element, widget) except Exception as e: self.printMsg(str(e)) return self.doc.toString(2)
def getStyleAsSld(layer, styleName): if layer.type() == layer.VectorLayer: document = QDomDocument() header = document.createProcessingInstruction("xml", "version=\"1.0\"") document.appendChild(header) root = document.createElementNS("http://www.opengis.net/sld", "StyledLayerDescriptor") root.setAttribute("version", "1.0.0") root.setAttribute("xmlns:ogc", "http://www.opengis.net/ogc") root.setAttribute("xmlns:sld", "http://www.opengis.net/sld") # root.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" ) # root.setAttribute( # "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ) document.appendChild(root) namedLayerNode = document.createElement("sld:NamedLayer") root.appendChild(namedLayerNode) nameNode = document.createElement("sld:Name") featureTypeStyleElem = document.createElement("sld:FeatureTypeStyle") namedLayerNode.appendChild(nameNode) nameNode.appendChild(document.createTextNode(styleName)) userNode = document.createElement("sld:UserStyle") namedLayerNode.appendChild(userNode) nameElem = document.createElement("sld:Name") nameElem.appendChild(document.createTextNode(styleName)) userNode.appendChild(nameElem) titleElem = document.createElement("sld:Title") titleElem.appendChild(document.createTextNode(styleName)) userNode.appendChild(titleElem) rule = layer.renderer().rootRule() props = {} # QgsStringMap() can be see as a python dictionary rule_to_sld(rule, document, featureTypeStyleElem, props) userNode.appendChild(featureTypeStyleElem) return str(document.toString(4)) elif layer.type() == layer.RasterLayer: renderer = layer.renderer() if isinstance(renderer, QgsSingleBandGrayRenderer): symbolizerCode = "<Opacity>%d</Opacity>" % renderer.opacity() symbolizerCode += ( "<ChannelSelection><GrayChannel><SourceChannelName>" + str(renderer.grayBand()) + "</SourceChannelName></GrayChannel></ChannelSelection>") sld = RASTER_SLD_TEMPLATE.replace("SYMBOLIZER_CODE", symbolizerCode).replace( "STYLE_NAME", layer.name()) return sld elif isinstance(renderer, QgsSingleBandPseudoColorRenderer): symbolizerCode = "<ColorMap>" # band = renderer.usesBands()[0] items = \ renderer.shader().rasterShaderFunction().colorRampItemList() for item in items: color = item.color rgb = '#%02x%02x%02x' % (color.red(), color.green(), color.blue()) symbolizerCode += ('<ColorMapEntry color="' + rgb + '" quantity="' + str(item.value) + '" />') symbolizerCode += "</ColorMap>" sld = RASTER_SLD_TEMPLATE.replace("SYMBOLIZER_CODE", symbolizerCode).replace( "STYLE_NAME", layer.name()) return sld else: # we use some default styles in case we have an # unsupported renderer sldpath = os.path.join(os.path.dirname(__file__), "..", "resources") if layer.bandCount() == 1: sldfile = os.path.join(sldpath, "grayscale.sld") else: sldfile = os.path.join(sldpath, "rgb.sld") with open(sldfile, 'r', newline='') as f: sld = f.read() return sld else: return None