44 if ( !file.open( QIODevice::ReadOnly ) )
46 errorMessage = QStringLiteral(
"Can not open file" );
52 if ( !doc.setContent( &file, &message ) )
54 errorMessage = message;
58 const QFileInfo fileinfo( file );
59 QDir::setCurrent( fileinfo.absoluteDir().path() );
65 return loadLayerDefinition( doc, project, rootGroup, errorMessage, context, insertMethod, insertPoint );
80 QVector<QDomNode> clonedSorted;
81 const auto constSortedLayerNodes = sortedLayerNodes;
82 for (
const QDomNode &node : constSortedLayerNodes )
84 clonedSorted << node.cloneNode();
86 QDomNode layersNode = doc.elementsByTagName( QStringLiteral(
"maplayers" ) ).at( 0 );
88 QDomNode childNode = layersNode.firstChild();
89 for (
int i = 0; ! childNode.isNull(); i++ )
91 layersNode.replaceChild( clonedSorted.at( i ), childNode );
92 childNode = childNode.nextSibling();
99 const QDomNodeList treeLayerNodes = doc.elementsByTagName( QStringLiteral(
"layer-tree-layer" ) );
100 for (
int i = 0; i < treeLayerNodes.length(); ++i )
102 const QDomNode treeLayerNode = treeLayerNodes.item( i );
103 QDomElement treeLayerElem = treeLayerNode.toElement();
104 const QString oldid = treeLayerElem.attribute( QStringLiteral(
"id" ) );
105 const QString layername = treeLayerElem.attribute( QStringLiteral(
"name" ) );
107 treeLayerElem.setAttribute( QStringLiteral(
"id" ), newid );
110 const QDomNodeList ids = doc.elementsByTagName( QStringLiteral(
"id" ) );
111 QDomNode idnode = ids.at( 0 );
112 for (
int j = 0; ! idnode.isNull() ; ++j )
114 idnode = ids.at( j );
115 const QDomElement idElem = idnode.toElement();
116 if ( idElem.text() == oldid )
118 idElem.firstChild().setNodeValue( newid );
123 const QDomNodeList vectorJoinNodes = doc.elementsByTagName( QStringLiteral(
"join" ) );
124 for (
int j = 0; j < vectorJoinNodes.size(); ++j )
126 const QDomNode joinNode = vectorJoinNodes.at( j );
127 const QDomElement joinElement = joinNode.toElement();
128 if ( joinElement.attribute( QStringLiteral(
"joinLayerId" ) ) == oldid )
130 joinNode.toElement().setAttribute( QStringLiteral(
"joinLayerId" ), newid );
135 const QDomNodeList dataDeps = doc.elementsByTagName( QStringLiteral(
"dataDependencies" ) );
136 for (
int i = 0; i < dataDeps.size(); i++ )
138 const QDomNodeList layers = dataDeps.at( i ).childNodes();
139 for (
int j = 0; j < layers.size(); j++ )
141 QDomElement elt = layers.at( j ).toElement();
142 if ( elt.attribute( QStringLiteral(
"id" ) ) == oldid )
144 elt.setAttribute( QStringLiteral(
"id" ), newid );
150 const QDomNodeList widgetConfig = doc.elementsByTagName( QStringLiteral(
"editWidget" ) );
151 for (
int i = 0; i < widgetConfig.size(); i++ )
153 const QDomNodeList config = widgetConfig.at( i ).childNodes();
154 for (
int j = 0; j < config.size(); j++ )
156 const QDomNodeList optMap = config.at( j ).childNodes();
157 for (
int z = 0; z < optMap.size(); z++ )
159 const QDomNodeList opts = optMap.at( z ).childNodes();
160 for (
int k = 0; k < opts.size(); k++ )
162 QDomElement opt = opts.at( k ).toElement();
163 if ( opt.attribute( QStringLiteral(
"value" ) ) == oldid )
165 opt.setAttribute( QStringLiteral(
"value" ), newid );
173 QDomElement layerTreeElem = doc.documentElement().firstChildElement( QStringLiteral(
"layer-tree-group" ) );
174 bool loadInLegend =
true;
175 if ( !layerTreeElem.isNull() )
178 loadInLegend =
false;
181 const QList<QgsMapLayer *> layers = QgsLayerDefinition::loadLayerDefinitionLayersInternal( doc, context, errorMessage );
186 const auto constLayers = layers;
189 layer->resolveReferences( project );
194 const QList<QgsLayerTreeNode *> nodes = root->
children();
198 switch ( insertMethod )
230 if ( !file.open( QFile::WriteOnly | QFile::Truncate ) )
232 errorMessage = file.errorString();
247 const QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
251 QTextStream qlayerstream( &file );
252 doc.save( qlayerstream, 2 );
258 Q_UNUSED( errorMessage )
259 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
260 doc.appendChild( qgiselm );
261 const QList<QgsLayerTreeNode *> nodes = selectedTreeNodes;
263 const auto constNodes = nodes;
271 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
272 const QList<QgsLayerTreeLayer *> layers = root->
findLayers();
273 const auto constLayers = layers;
276 if ( ! layer->layer() )
278 QgsDebugMsgLevel( QStringLiteral(
"Not a valid map layer: skipping %1" ).arg( layer->name( ) ), 4 );
281 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
282 layer->layer()->writeLayerXml( layerelm, doc, context );
283 layerselm.appendChild( layerelm );
285 qgiselm.appendChild( layerselm );
291 QDomDocument doc( QStringLiteral(
"qgis-layer-definition" ) );
292 QDomElement qgiselm = doc.createElement( QStringLiteral(
"qlr" ) );
293 doc.appendChild( qgiselm );
294 QDomElement layerselm = doc.createElement( QStringLiteral(
"maplayers" ) );
295 const auto constLayers = layers;
298 QDomElement layerelm = doc.createElement( QStringLiteral(
"maplayer" ) );
299 layer->writeLayerXml( layerelm, doc, context );
300 layerselm.appendChild( layerelm );
302 qgiselm.appendChild( layerselm );
308 QString errorMessage;
309 return loadLayerDefinitionLayersInternal( document, context, errorMessage );
312QList<QgsMapLayer *> QgsLayerDefinition::loadLayerDefinitionLayersInternal( QDomDocument &document,
QgsReadWriteContext &context, QString &errorMessage )
314 QList<QgsMapLayer *> layers;
315 QDomElement layerElem = document.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
317 if ( layerElem.isNull() )
319 layerElem = document.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
322 while ( ! layerElem.isNull() )
324 const QString type = layerElem.attribute( QStringLiteral(
"type" ) );
343 const QString
typeName = layerElem.attribute( QStringLiteral(
"name" ) );
382 errorMessage = QObject::tr(
"Unsupported layer type: %1" ).arg( type );
384 layerElem = layerElem.nextSiblingElement( QStringLiteral(
"maplayer" ) );
391 QFile file( qlrfile );
392 if ( !file.open( QIODevice::ReadOnly ) )
395 return QList<QgsMapLayer *>();
399 if ( !doc.setContent( &file ) )
402 return QList<QgsMapLayer *>();
411void QgsLayerDefinition::DependencySorter::init(
const QDomDocument &doc )
414 QMap< QString, QVector< QString > > dependencies;
415 QStringList sortedLayers;
416 QList< QPair<QString, QDomNode> > layersToSort;
417 QStringList layerIds;
419 QDomElement layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"projectlayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
421 if ( layerElem.isNull() )
423 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayers" ) ).firstChildElement( QStringLiteral(
"maplayer" ) );
426 if ( layerElem.isNull() )
428 layerElem = doc.documentElement().firstChildElement( QStringLiteral(
"maplayer" ) );
431 const QDomElement &firstElement { layerElem };
433 QVector<QString> deps;
434 while ( !layerElem.isNull() )
438 const QString
id = layerElem.namedItem( QStringLiteral(
"id" ) ).toElement().text();
442 const QDomElement layerDependenciesElem = layerElem.firstChildElement( QStringLiteral(
"layerDependencies" ) );
443 if ( !layerDependenciesElem.isNull() )
445 const QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( QStringLiteral(
"layer" ) );
446 for (
int j = 0; j < dependencyList.size(); ++j )
448 const QDomElement depElem = dependencyList.at( j ).toElement();
449 deps << depElem.attribute( QStringLiteral(
"id" ) );
452 dependencies[id] = deps;
457 mSortedLayerNodes << layerElem;
458 mSortedLayerIds << id;
462 layersToSort << qMakePair(
id, layerElem );
463 mDependentLayerIds.insert(
id );
465 layerElem = layerElem.nextSiblingElement( );
469 const auto constDependencies = dependencies;
470 for (
const QVector< QString > &ids : constDependencies )
472 const auto constIds = ids;
473 for (
const QString &depId : constIds )
475 if ( !dependencies.contains( depId ) )
478 mHasMissingDependency =
true;
479 layerElem = firstElement;
480 while ( ! layerElem.isNull() )
482 mSortedLayerNodes << layerElem;
483 layerElem = layerElem.nextSiblingElement( );
485 mSortedLayerIds = layerIds;
495 while ( !layersToSort.empty() && !mHasCycle )
497 QList< QPair<QString, QDomNode> >::iterator it = layersToSort.begin();
498 while ( it != layersToSort.end() )
500 const QString idToSort = it->first;
501 const QDomNode node = it->second;
503 bool resolved =
true;
504 const auto deps { dependencies.value( idToSort ) };
505 for (
const QString &dep : deps )
507 if ( !sortedLayers.contains( dep ) )
515 sortedLayers << idToSort;
516 mSortedLayerNodes << node;
517 mSortedLayerIds << idToSort;
518 it = layersToSort.erase( it );
531 , mHasMissingDependency( false )
538 , mHasMissingDependency( false )
540 QString qgsProjectFile = fileName;
542 if ( fileName.endsWith( QLatin1String(
".qgz" ), Qt::CaseInsensitive ) )
544 archive.
unzip( fileName );
549 QFile pFile( qgsProjectFile );
550 ( void )pFile.open( QIODevice::ReadOnly );
551 ( void )doc.setContent( &pFile );
557 return mDependentLayerIds.contains( layerId );
LayerTreeInsertionMethod
Layer tree insertion methods.
@ TopOfTree
Layers are added at the top of the layer tree.
@ AboveInsertionPoint
Layers are added in the tree above the insertion point.
FilePathType
File path types.
LayerType
Types of layers that can be added to a map.
@ Group
Composite group layer. Added in QGIS 3.24.
@ Plugin
Plugin based layer.
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
@ Mesh
Mesh layer. Added in QGIS 3.2.
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
Contains information about the context in which a coordinate transform is executed.
static QString ensureFileNameHasExtension(const QString &fileName, const QStringList &extensions)
Ensures that a fileName ends with an extension from the provided list of extensions.
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
Class used to work with layer dependencies stored in a XML project or layer definition file.
bool hasMissingDependency() const
Whether some dependency is missing.
bool isLayerDependent(const QString &layerId) const
Returns whether the layer associated with thelayerId is dependent from another layer.
DependencySorter(const QDomDocument &doc)
Constructor.
QVector< QDomNode > sortedLayerNodes() const
Gets the layer nodes in an order where they can be loaded incrementally without dependency break.
static QDomDocument exportLayerDefinitionLayers(const QList< QgsMapLayer * > &layers, const QgsReadWriteContext &context)
Returns the given layer as a layer definition document Layer definitions store the data source as wel...
static QList< QgsMapLayer * > loadLayerDefinitionLayers(QDomDocument &document, QgsReadWriteContext &context)
Creates new layers from a layer definition document.
static bool loadLayerDefinition(const QString &path, QgsProject *project, QgsLayerTreeGroup *rootGroup, QString &errorMessage, Qgis::LayerTreeInsertionMethod insertMethod=Qgis::LayerTreeInsertionMethod::OptimalInInsertionGroup, const QgsLayerTreeRegistryBridge::InsertionPoint *insertPoint=nullptr)
Loads the QLR at path into QGIS.
static bool exportLayerDefinition(const QString &path, const QList< QgsLayerTreeNode * > &selectedTreeNodes, QString &errorMessage)
Exports the selected layer tree nodes to a QLR file.
Layer tree group node serves as a container for layers and further groups.
void resolveReferences(const QgsProject *project, bool looseMatching=false) override
Calls resolveReferences() on child tree nodes.
void writeXml(QDomElement &parentElement, const QgsReadWriteContext &context) override
Write group (tree) as XML element <layer-tree-group> and add it to the given parent element.
void addChildNode(QgsLayerTreeNode *node)
Append an existing node.
void insertChildNodes(int index, const QList< QgsLayerTreeNode * > &nodes)
Insert existing nodes at specified position.
void readChildrenFromXml(QDomElement &element, const QgsReadWriteContext &context)
Read children from XML and append them to the group.
QList< QgsLayerTreeLayer * > findLayers() const
Find all layer nodes.
Layer tree node points to a map layer.
This class is a base class for nodes in a layer tree.
QList< QgsLayerTreeNode * > abandonChildren()
Removes the children, disconnect all the forwarded and external signals and sets their parent to null...
QList< QgsLayerTreeNode * > children()
Gets list of children of the node. Children are owned by the parent.
virtual QgsLayerTreeNode * clone() const =0
Create a copy of the node. Returns new instance.
static Qgis::LayerType typeFromString(const QString &string, bool &ok)
Returns the map layer type corresponding a string value.
Base class for all map layer types.
static QString generateId(const QString &layerName)
Generates an unique identifier for this layer, the generate ID is prefixed by layerName.
bool readLayerXml(const QDomElement &layerElement, QgsReadWriteContext &context, QgsMapLayer::ReadFlags flags=QgsMapLayer::ReadFlags(), QgsDataProvider *preloadedProvider=nullptr)
Sets state from DOM document.
Represents a mesh layer supporting display of data on structured or unstructured meshes.
Resolves relative paths into absolute paths and vice versa.
QgsPluginLayer * createLayer(const QString &typeName, const QString &uri=QString())
Returns new layer if corresponding plugin has been found else returns nullptr.
Represents a map layer supporting display of point clouds.
Class allowing to manage the zip/unzip actions on project file.
QString projectFile() const
Returns the current .qgs project file or an empty string if there's none.
bool unzip(const QString &zipFilename) override
Clear the current content of this archive and unzip.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QList< QgsMapLayer * > addMapLayers(const QList< QgsMapLayer * > &mapLayers, bool addToLegend=true, bool takeOwnership=true)
Add a list of layers to the map of loaded layers.
static QgsProject * instance()
Returns the QgsProject singleton instance.
Represents a raster layer.
The class is used as a container of context for various read/write operations on other objects.
void setProjectTranslator(QgsProjectTranslator *projectTranslator)
Sets the project translator.
void setPathResolver(const QgsPathResolver &resolver)
Sets up path resolver for conversion between relative and absolute paths.
Represents a map layer supporting display of tiled scene objects.
Represents a vector layer which manages a vector based data sets.
Implements a map layer that is dedicated to rendering of vector tiles.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
Setting options for loading group layers.
A structure to define the insertion point to the layer tree.
QgsLayerTreeGroup * group