QGIS API Documentation  3.6.0-Noosa (5873452)
qgsproject.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgsproject.h
3 
4  Implements persistent project state.
5 
6  -------------------
7  begin : July 23, 2004
8  copyright : (C) 2004 by Mark Coletti
9  email : mcoletti at gmail.com
10  ***************************************************************************/
11 
12 /***************************************************************************
13  * *
14  * This program is free software; you can redistribute it and/or modify *
15  * it under the terms of the GNU General Public License as published by *
16  * the Free Software Foundation; either version 2 of the License, or *
17  * (at your option) any later version. *
18  * *
19  ***************************************************************************/
20 
21 #ifndef QGSPROJECT_H
22 #define QGSPROJECT_H
23 
24 #include "qgis_core.h"
25 #include "qgis_sip.h"
26 #include <memory>
27 #include <QHash>
28 #include <QList>
29 #include <QObject>
30 #include <QPair>
31 #include <QFileInfo>
32 #include <QStringList>
33 #include <QTranslator>
34 
35 #include "qgsunittypes.h"
36 #include "qgssnappingconfig.h"
37 #include "qgsprojectversion.h"
41 #include "qgsprojectproperty.h"
42 #include "qgsmaplayerstore.h"
43 #include "qgsarchive.h"
44 #include "qgsreadwritecontext.h"
45 #include "qgsprojectmetadata.h"
46 #include "qgstranslationcontext.h"
47 #include "qgsprojecttranslator.h"
49 #include "qgscolorscheme.h"
50 
51 class QFileInfo;
52 class QDomDocument;
53 class QDomElement;
54 class QDomNode;
55 
56 class QgsLayerTreeGroup;
58 class QgsMapLayer;
60 class QgsPathResolver;
62 class QgsProjectStorage;
63 class QgsRelationManager;
64 class QgsTolerance;
66 class QgsVectorLayer;
68 class QgsLayoutManager;
69 class QgsLayerTree;
72 class QgsMapLayer;
73 
89 class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenerator, public QgsProjectTranslator
90 {
91  Q_OBJECT
92  Q_PROPERTY( QStringList nonIdentifiableLayers READ nonIdentifiableLayers WRITE setNonIdentifiableLayers NOTIFY nonIdentifiableLayersChanged )
93  Q_PROPERTY( QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged )
94  Q_PROPERTY( QString homePath READ homePath WRITE setPresetHomePath NOTIFY homePathChanged )
95  Q_PROPERTY( QgsCoordinateReferenceSystem crs READ crs WRITE setCrs NOTIFY crsChanged )
96  Q_PROPERTY( QgsCoordinateTransformContext transformContext READ transformContext WRITE setTransformContext NOTIFY transformContextChanged )
97  Q_PROPERTY( QString ellipsoid READ ellipsoid WRITE setEllipsoid NOTIFY ellipsoidChanged )
98  Q_PROPERTY( QgsMapThemeCollection *mapThemeCollection READ mapThemeCollection NOTIFY mapThemeCollectionChanged )
99  Q_PROPERTY( QgsSnappingConfig snappingConfig READ snappingConfig WRITE setSnappingConfig NOTIFY snappingConfigChanged )
100  Q_PROPERTY( QgsRelationManager *relationManager READ relationManager )
101  Q_PROPERTY( QList<QgsVectorLayer *> avoidIntersectionsLayers READ avoidIntersectionsLayers WRITE setAvoidIntersectionsLayers NOTIFY avoidIntersectionsLayersChanged )
102  Q_PROPERTY( QgsProjectMetadata metadata READ metadata WRITE setMetadata NOTIFY metadataChanged )
103 
104  public:
106  static QgsProject *instance();
107 
113  explicit QgsProject( QObject *parent SIP_TRANSFERTHIS = nullptr );
114 
115  ~QgsProject() override;
116 
126  void setTitle( const QString &title );
127 
134  QString title() const;
135 
139  bool isDirty() const;
140 
147  void setFileName( const QString &name );
148 
155  QString fileName() const;
156 
168  Q_DECL_DEPRECATED QFileInfo fileInfo() const SIP_DEPRECATED;
169 
176  QgsProjectStorage *projectStorage() const;
177 
182  QDateTime lastModified() const;
183 
189  QString absoluteFilePath() const;
190 
196  QString absolutePath() const;
197 
202  QString baseName() const;
203 
211 
218  void setCrs( const QgsCoordinateReferenceSystem &crs );
219 
226  QString ellipsoid() const;
227 
234  void setEllipsoid( const QString &ellipsoid );
235 
236 
246  QgsCoordinateTransformContext transformContext() const;
247 
257  void setTransformContext( const QgsCoordinateTransformContext &context );
258 
264  void clear();
265 
271  bool read( const QString &filename );
272 
277  bool read();
278 
288  bool readLayer( const QDomNode &layerNode );
289 
298  bool write( const QString &filename );
299 
305  bool write();
306 
316  bool writeEntry( const QString &scope, const QString &key, bool value ) SIP_PYNAME( writeEntryBool );
317 
327  bool writeEntry( const QString &scope, const QString &key, double value ) SIP_PYNAME( writeEntryDouble );
328 
337  bool writeEntry( const QString &scope, const QString &key, int value );
338 
347  bool writeEntry( const QString &scope, const QString &key, const QString &value );
348 
357  bool writeEntry( const QString &scope, const QString &key, const QStringList &value );
358 
365  QStringList readListEntry( const QString &scope, const QString &key, const QStringList &def = QStringList(), bool *ok = nullptr ) const;
366 
367  QString readEntry( const QString &scope, const QString &key, const QString &def = QString(), bool *ok = nullptr ) const;
368  int readNumEntry( const QString &scope, const QString &key, int def = 0, bool *ok = nullptr ) const;
369  double readDoubleEntry( const QString &scope, const QString &key, double def = 0, bool *ok = nullptr ) const;
370  bool readBoolEntry( const QString &scope, const QString &key, bool def = false, bool *ok = nullptr ) const;
371 
372 
374  bool removeEntry( const QString &scope, const QString &key );
375 
376 
382  QStringList entryList( const QString &scope, const QString &key ) const;
383 
389  QStringList subkeyList( const QString &scope, const QString &key ) const;
390 
391 
395  // TODO Now slightly broken since re-factoring. Won't print out top-level key
396  // and redundantly prints sub-keys.
397  void dumpProperties() const;
398 
404  QgsPathResolver pathResolver() const;
405 
411  QString writePath( const QString &filename ) const;
412 
414  QString readPath( const QString &filename ) const;
415 
417  QString error() const;
418 
423  void setBadLayerHandler( QgsProjectBadLayerHandler *handler SIP_TRANSFER );
424 
426  QString layerIsEmbedded( const QString &id ) const;
427 
433  bool createEmbeddedLayer( const QString &layerId, const QString &projectFilePath, QList<QDomNode> &brokenNodes,
434  bool saveFlag = true ) SIP_SKIP;
435 
440  QgsLayerTreeGroup *createEmbeddedGroup( const QString &groupName, const QString &projectFilePath, const QStringList &invisibleLayers );
441 
443  void setTopologicalEditing( bool enabled );
444 
446  bool topologicalEditing() const;
447 
454  QgsUnitTypes::DistanceUnit distanceUnits() const;
455 
462  void setDistanceUnits( QgsUnitTypes::DistanceUnit unit );
463 
469  QgsUnitTypes::AreaUnit areaUnits() const;
470 
477  void setAreaUnits( QgsUnitTypes::AreaUnit unit );
478 
491  QString homePath() const;
492 
505  QString presetHomePath() const;
506 
507  QgsRelationManager *relationManager() const;
508 
515  const QgsLayoutManager *layoutManager() const SIP_SKIP;
516 
522  QgsLayoutManager *layoutManager();
523 
528  QgsLayerTree *layerTreeRoot() const;
529 
534  QgsLayerTreeRegistryBridge *layerTreeRegistryBridge() const { return mLayerTreeRegistryBridge; }
535 
541  QgsMapThemeCollection *mapThemeCollection();
542 
547  QgsAnnotationManager *annotationManager();
548 
553  const QgsAnnotationManager *annotationManager() const SIP_SKIP;
554 
559  Q_DECL_DEPRECATED void setNonIdentifiableLayers( const QList<QgsMapLayer *> &layers );
560 
565  Q_DECL_DEPRECATED void setNonIdentifiableLayers( const QStringList &layerIds );
566 
571  Q_DECL_DEPRECATED QStringList nonIdentifiableLayers() const;
572 
580  bool autoTransaction() const;
581 
591  void setAutoTransaction( bool autoTransaction );
592 
601  QMap< QPair< QString, QString>, QgsTransactionGroup *> transactionGroups() SIP_SKIP;
602 
610  QgsTransactionGroup *transactionGroup( const QString &providerKey, const QString &connString );
611 
617  bool evaluateDefaultValues() const;
618 
624  void setEvaluateDefaultValues( bool evaluateDefaultValues );
625 
627 
633  QgsSnappingConfig snappingConfig() const;
634 
640  QList<QgsVectorLayer *> avoidIntersectionsLayers() const;
641 
647  void setAvoidIntersectionsLayers( const QList<QgsVectorLayer *> &layers );
648 
654  QVariantMap customVariables() const;
655 
660  void setCustomVariables( const QVariantMap &customVariables );
661 
666  void setLabelingEngineSettings( const QgsLabelingEngineSettings &settings );
667 
672  const QgsLabelingEngineSettings &labelingEngineSettings() const;
673 
674  //
675  // Functionality from QgsMapLayerRegistry
676  //
677 
682  QgsMapLayerStore *layerStore();
683 
688  SIP_SKIP const QgsMapLayerStore *layerStore() const;
689 
691  int count() const;
692 
694  int validCount() const;
695 
703  QgsMapLayer *mapLayer( const QString &layerId ) const;
704 
705 #ifndef SIP_RUN
706 
722  template <class T>
723  T mapLayer( const QString &layerId ) const
724  {
725  return qobject_cast<T>( mapLayer( layerId ) );
726  }
727 #endif
728 
736  QList<QgsMapLayer *> mapLayersByName( const QString &layerName ) const;
737 
746  QMap<QString, QgsMapLayer *> mapLayers( const bool validOnly = false ) const;
747 
751  bool isZipped() const;
752 
753 #ifndef SIP_RUN
754 
766  template <typename T>
767  QVector<T> layers() const
768  {
769  return mLayerStore->layers<T>();
770  }
771 #endif
772 
798  QList<QgsMapLayer *> addMapLayers( const QList<QgsMapLayer *> &mapLayers SIP_TRANSFER,
799  bool addToLegend = true,
800  bool takeOwnership SIP_PYARGREMOVE = true );
801 
829  QgsMapLayer *addMapLayer( QgsMapLayer *mapLayer SIP_TRANSFER,
830  bool addToLegend = true,
831  bool takeOwnership SIP_PYARGREMOVE = true );
832 
847  void removeMapLayers( const QStringList &layerIds );
848 
849  //TODO QGIS 4.0 - add PyName alias to avoid list type conversion error
850 
864  void removeMapLayers( const QList<QgsMapLayer *> &layers );
865 
879  void removeMapLayer( const QString &layerId );
880 
894  void removeMapLayer( QgsMapLayer *layer );
895 
903  QgsMapLayer *takeMapLayer( QgsMapLayer *layer ) SIP_TRANSFERBACK;
904 
915  void removeAllMapLayers();
916 
922  void reloadAllLayers();
923 
928  QgsCoordinateReferenceSystem defaultCrsForNewLayers() const;
929 
941  void setTrustLayerMetadata( bool trust );
942 
953  bool trustLayerMetadata() const { return mTrustLayerMetadata; }
954 
960  const QgsAuxiliaryStorage *auxiliaryStorage() const SIP_SKIP;
961 
967  QgsAuxiliaryStorage *auxiliaryStorage();
968 
975  const QgsProjectMetadata &metadata() const;
976 
983  void setMetadata( const QgsProjectMetadata &metadata );
984 
993  Q_DECL_DEPRECATED QSet<QgsMapLayer *> requiredLayers() const;
994 
1003  Q_DECL_DEPRECATED void setRequiredLayers( const QSet<QgsMapLayer *> &layers );
1004 
1011  void setProjectColors( const QgsNamedColorList &colors );
1012 
1017  void generateTsFile( const QString &locale );
1018 
1029  QString translate( const QString &context, const QString &sourceText, const char *disambiguation = nullptr, int n = -1 ) const override;
1030 
1031  signals:
1032 
1040  void cleared();
1041 
1045  void readProject( const QDomDocument & );
1046 
1050  void readProjectWithContext( const QDomDocument &, QgsReadWriteContext &context );
1051 
1055  void writeProject( QDomDocument & );
1056 
1065  void readMapLayer( QgsMapLayer *mapLayer, const QDomElement &layerNode );
1066 
1075  void writeMapLayer( QgsMapLayer *mapLayer, QDomElement &layerElem, QDomDocument &doc );
1076 
1080  void projectSaved();
1081 
1085  void oldProjectVersionWarning( const QString & );
1086 
1092  void layerLoaded( int i, int n );
1093 
1095  void loadingLayer( const QString &layerName );
1096 
1103  void loadingLayerMessageReceived( const QString &layerName, const QList<QgsReadWriteContext::ReadWriteMessage> &messages );
1104 
1109  Q_DECL_DEPRECATED void nonIdentifiableLayersChanged( QStringList nonIdentifiableLayers );
1110 
1112  void fileNameChanged();
1113 
1120  void homePathChanged();
1121 
1125  void snappingConfigChanged( const QgsSnappingConfig &config );
1126 
1131  void customVariablesChanged();
1132 
1138  void crsChanged();
1139 
1147  void ellipsoidChanged( const QString &ellipsoid );
1148 
1149 
1156  void transformContextChanged();
1157 
1162  void missingDatumTransforms( const QStringList &missingTransforms );
1163 
1170  void transactionGroupsChanged();
1171 
1177  void topologicalEditingChanged();
1178 
1184  void avoidIntersectionsLayersChanged();
1185 
1197  void mapThemeCollectionChanged();
1198 
1203  void labelingEngineSettingsChanged();
1204 
1211  void metadataChanged();
1212 
1219  void projectColorsChanged();
1220 
1221  //
1222  // signals from QgsMapLayerRegistry
1223  //
1224 
1232  void layersWillBeRemoved( const QStringList &layerIds );
1233 
1241  void layersWillBeRemoved( const QList<QgsMapLayer *> &layers );
1242 
1252  void layerWillBeRemoved( const QString &layerId );
1253 
1263  void layerWillBeRemoved( QgsMapLayer *layer );
1264 
1271  void layersRemoved( const QStringList &layerIds );
1272 
1281  void layerRemoved( const QString &layerId );
1282 
1283  //TODO QGIS 4.0 - rename to past tense
1284 
1291  void removeAll();
1292 
1303  void layersAdded( const QList<QgsMapLayer *> &layers );
1304 
1311  void layerWasAdded( QgsMapLayer *layer );
1312 
1321  void legendLayersAdded( const QList<QgsMapLayer *> &layers );
1322 
1330  void isDirtyChanged( bool dirty );
1331 
1332  public slots:
1333 
1339  void setSnappingConfig( const QgsSnappingConfig &snappingConfig );
1340 
1341  // TODO QGIS 4.0 - rename b to dirty
1342 
1350  void setDirty( bool b = true );
1351 
1360  void setPresetHomePath( const QString &path );
1361 
1371  void registerTranslatableContainers( QgsTranslationContext *translationContext, QgsAttributeEditorContainer *parent, const QString &layerId );
1372 
1379  void registerTranslatableObjects( QgsTranslationContext *translationContext );
1380 
1381  private slots:
1382  void onMapLayersAdded( const QList<QgsMapLayer *> &layers );
1383  void onMapLayersRemoved( const QList<QgsMapLayer *> &layers );
1384  void cleanTransactionGroups( bool force = false );
1385 
1386  private:
1387 
1388  static QgsProject *sProject;
1389 
1398  static void setInstance( QgsProject *project ) SIP_SKIP;
1399 
1407  bool _getMapLayers( const QDomDocument &doc, QList<QDomNode> &brokenNodes );
1408 
1413  void setError( const QString &errorMessage ) SIP_SKIP;
1414 
1419  void clearError() SIP_SKIP;
1420 
1425  bool addLayer( const QDomElement &layerElem, QList<QDomNode> &brokenNodes, QgsReadWriteContext &context ) SIP_SKIP;
1426 
1428  void initializeEmbeddedSubtree( const QString &projectFilePath, QgsLayerTreeGroup *group ) SIP_SKIP;
1429 
1431  void loadEmbeddedNodes( QgsLayerTreeGroup *group ) SIP_SKIP;
1432 
1434  bool readProjectFile( const QString &filename );
1435 
1437  bool writeProjectFile( const QString &filename );
1438 
1440  bool unzip( const QString &filename );
1441 
1443  bool zip( const QString &filename );
1444 
1446  bool saveAuxiliaryStorage( const QString &filename = QString() );
1447 
1448  std::unique_ptr< QgsMapLayerStore > mLayerStore;
1449 
1450  QString mErrorMessage;
1451 
1452  QgsProjectBadLayerHandler *mBadLayerHandler = nullptr;
1453 
1459  QHash< QString, QPair< QString, bool> > mEmbeddedLayers;
1460 
1461  QgsSnappingConfig mSnappingConfig;
1462 
1463  QgsRelationManager *mRelationManager = nullptr;
1464 
1465  std::unique_ptr<QgsAnnotationManager> mAnnotationManager;
1466  std::unique_ptr<QgsLayoutManager> mLayoutManager;
1467 
1468  QgsLayerTree *mRootGroup = nullptr;
1469 
1470  QgsLayerTreeRegistryBridge *mLayerTreeRegistryBridge = nullptr;
1471 
1473  QMap< QPair< QString, QString>, QgsTransactionGroup *> mTransactionGroups;
1474 
1475  std::unique_ptr<QgsMapThemeCollection> mMapThemeCollection;
1476 
1477  std::unique_ptr<QgsLabelingEngineSettings> mLabelingEngineSettings;
1478 
1479  QVariantMap mCustomVariables;
1480 
1481  std::unique_ptr<QgsProjectArchive> mArchive;
1482 
1483  std::unique_ptr<QgsAuxiliaryStorage> mAuxiliaryStorage;
1484 
1485  QFile mFile; // current physical project file
1486 
1491  QString mHomePath;
1492  mutable QgsProjectPropertyKey mProperties; // property hierarchy, TODO: this shouldn't be mutable
1493  bool mAutoTransaction = false; // transaction grouped editing
1494  bool mEvaluateDefaultValues = false; // evaluate default values immediately
1496  bool mDirty = false; // project has been modified since it has been read or saved
1497  int mDirtyBlockCount = 0;
1498  bool mTrustLayerMetadata = false;
1499 
1500  QgsCoordinateTransformContext mTransformContext;
1501 
1502  QgsProjectMetadata mMetadata;
1503 
1504  std::unique_ptr< QTranslator > mTranslator;
1505 
1506  bool mIsBeingDeleted = false;
1507 
1509 
1510  // Required by QGIS Server for switching the current project instance
1511  friend class QgsConfigCache;
1512 };
1513 
1535 class CORE_EXPORT QgsProjectDirtyBlocker
1536 {
1537  public:
1538 
1545  : mProject( project )
1546  {
1547  mProject->mDirtyBlockCount++;
1548  }
1549 
1551  QgsProjectDirtyBlocker( const QgsProjectDirtyBlocker &other ) = delete;
1552 
1554  QgsProjectDirtyBlocker &operator=( const QgsProjectDirtyBlocker &other ) = delete;
1555 
1557  {
1558  mProject->mDirtyBlockCount--;
1559  }
1560 
1561  private:
1562  QgsProject *mProject = nullptr;
1563 
1564 #ifdef SIP_RUN
1566 #endif
1567 };
1568 
1574 CORE_EXPORT QgsProjectVersion getVersion( QDomDocument const &doc ) SIP_SKIP;
1575 
1576 #endif
Layer tree group node serves as a container for layers and further groups.
The class is used as a container of context for various read/write operations on other objects...
Base class for all map layer types.
Definition: qgsmaplayer.h:64
#define SIP_TRANSFERTHIS
Definition: qgis_sip.h:46
Manages storage of a set of QgsAnnotation annotation objects.
Helper functions for various unit types.
Definition: qgsunittypes.h:38
Class providing some utility methods to manage auxiliary storage.
const QgsCoordinateReferenceSystem & crs
#define SIP_TRANSFERBACK
Definition: qgis_sip.h:41
virtual QgsExpressionContext createExpressionContext() const =0
This method needs to be reimplemented in all classes which implement this interface and return an exp...
T mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layerId converted to type T.
Definition: qgsproject.h:723
bool trustLayerMetadata() const
Returns true if the trust option is activated, false otherwise.
Definition: qgsproject.h:953
Namespace with helper functions for layer tree operations.
Definition: qgslayertree.h:32
CORE_EXPORT bool unzip(const QString &zip, const QString &dir, QStringList &files)
Unzip a zip file in an output directory.
Definition: qgsziputils.cpp:34
#define SIP_SKIP
Definition: qgis_sip.h:119
CORE_EXPORT QgsProjectVersion getVersion(QDomDocument const &doc)
Returns the version string found in the given DOM document.
Definition: qgsproject.cpp:845
A class to describe the version of a project.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
This is the class is providing tolerance value in map unit values.
Definition: qgstolerance.h:32
Listens to the updates in map layer registry and does changes in layer tree.
#define SIP_TRANSFER
Definition: qgis_sip.h:36
QList< QPair< QColor, QString > > QgsNamedColorList
List of colors paired with a friendly display name identifying the color.
Reads and writes project states.
Definition: qgsproject.h:89
Contains information about the context in which a coordinate transform is executed.
Wherever an object of this class is available, the derived translate function can be called from...
Manages storage of a set of layouts.
#define SIP_DEPRECATED
Definition: qgis_sip.h:99
Used for the collecting of strings from projects for translation and creation of ts files...
Abstract interface for generating an expression context.
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
The derived translate() translates with QTranslator and qm file the sourceText.
Project property key node.
Cache for server configuration.
#define SIP_PYARGREMOVE
Definition: qgis_sip.h:139
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
Definition: qgsproject.h:767
This class manages a set of relations between layers.
Stores global configuration for labeling engine.
This class represents a coordinate reference system (CRS).
This is a container for attribute editors, used to group them visually in the attribute form if it is...
Abstract interface for project storage - to be implemented by various backends and registered in QgsP...
QgsProjectDirtyBlocker(QgsProject *project)
Constructor for QgsProjectDirtyBlocker.
Definition: qgsproject.h:1544
Temporarily blocks QgsProject "dirtying" for the lifetime of the object.
Definition: qgsproject.h:1535
A storage object for map layers, in which the layers are owned by the store and have their lifetime b...
Container class that allows storage of map themes consisting of visible map layers and layer styles...
This is a container for configuration of the snapping of the project.
Resolves relative paths into absolute paths and vice versa.
Represents a vector layer which manages a vector based data sets.
CORE_EXPORT bool zip(const QString &zip, const QStringList &files)
Zip the list of files in the zip file.
Interface for classes that handle missing layer files when reading project file.
#define SIP_PYNAME(name)
Definition: qgis_sip.h:74
A structured metadata store for a map layer.