Geographic Information Systems Asked by johnzet on February 15, 2021
I use QgsLayerDefinition.loadLayerDefinition(path, project, rootGroup)
in my code. But this method changes ids of loaded layers. I need the codes to be old. Is there any way to change ids (for example any custom) of layers after loading layer definitions? Or have any other ideas?
To solve my problem, it was enough for me to use the idea of methods loadLayerDefinition
, using the minimum functionality of these methods (+I added some restriction).
def loadLayerDefinitionCustom(self, path, project, rootGroup):
file = QFile(path)
doc = QtXml.QDomDocument()
doc.setContent(file)
context = QgsReadWriteContext()
context.setPathResolver( QgsPathResolver(path))
context.setProjectTranslator(project)
return self.loadLayerDefinitionDocCustom( doc, project, rootGroup, context )
def loadLayerDefinitionDocCustom(self, doc, project, rootGroup, context):
root = QgsLayerTreeGroup()
# # check for id layers in project
# map_layers = list(QgsProject.instance().mapLayers().keys())
# treeLayerNodes = doc.elementsByTagName("maplayer")
# for i in range(treeLayerNodes.count()):
# node = treeLayerNodes.at(i)
# idval = node.firstChildElement("id").text()
# if idval in map_layers:
# self.iface.messageBar().pushMessage(
# u"Map already consists layer ID",
# u"",
# duration=5,
# level=2
# )
# raise Exception("Map already consists layer ID " + idval)
layerTreeElem = doc.documentElement().firstChildElement( "layer-tree-group" )
loadInLegend = True
if layerTreeElem is not None:
root.readChildrenFromXml( layerTreeElem, context )
loadInLegend = False
layers = QgsLayerDefinition.loadLayerDefinitionLayers( doc, context )
project.addMapLayers(layers, loadInLegend)
for layer in layers:
layer.resolveReferences(project)
root.resolveReferences(project)
nodes = root.children()
for idx, n in enumerate(nodes):
root.takeChild(n)
rootGroup.insertChildNodes(0, nodes)
return True
Correct answer by johnzet on February 15, 2021
Use QgsLayerDefinition.loadLayerDefinitionLayers
.
QgsLayerDefinition::loadLayerDefinitionLayers(QDomDocument & document, QgsReadWriteContext & context)
Creates new layers from a layer definition document. This is a low-level routine that does not resolve layer ID conflicts, dependencies and joins
Therefore you should use loadLayerDefinitionLayers
instead of loadLayerDefinition
so that you don't need to change ids.
layer_list = QgsLayerDefinition().loadLayerDefinitionLayers(path)
QgsProject.instance().addMapLayers(layer_list)
Answered by Kadir Şahbaz on February 15, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP