Class: QgsProject

class qgis.core.QgsProject(parent: QObject = None)

Bases: PyQt5.QtCore.QObject, qgis._core.QgsExpressionContextGenerator, qgis._core.QgsProjectTranslator

Create a new QgsProject.

Most of the time you want to use QgsProject.instance() instead as many components of QGIS work with the singleton.

Reads and writes project states.

note

Has two general kinds of state to make persistent. (I.e., to read and write.) First, QGIS proprietary information. Second plug-in information.

A singleton since there shall only be one active project at a time; and provides canonical location for plug-ins and main app to find/set properties.

Enums

Methods

absoluteFilePath

Returns full absolute path to the project file if the project is stored in a file system - derived from fileName().

absolutePath

Returns full absolute path to the project folder if the project is stored in a file system - derived from fileName().

accept

Accepts the specified style entity visitor, causing it to visit all style entities associated with the project.

addMapLayer

Add a layer to the map of loaded layers.

addMapLayers

Add a list of layers to the map of loaded layers.

annotationManager

Returns pointer to the project’s annotation manager.

areaUnits

Convenience function to query default area measurement units for project.

autoTransaction

Transactional editing means that on supported datasources (postgres databases) the edit state of all tables that originate from the same database are synchronized and executed in a server side transaction.

auxiliaryStorage

Returns the current auxiliary storage.

avoidIntersectionsLayers

A list of layers with which intersections should be avoided.

baseName

Returns the base name of the project file without the path and without extension - derived from fileName().

childEvent

clear

Clears the project, removing all settings and resetting it back to an empty, default state.

connectNotify

count

Returns the number of registered layers.

createEmbeddedGroup

Create layer group instance defined in an arbitrary project file.

createExpressionContext

crs

Returns the project’s native coordinate reference system.

customEvent

customVariables

A map of custom project variables.

defaultCrsForNewLayers

Returns the default CRS for new layers based on the settings and the current project CRS

disconnectNotify

distanceUnits

Convenience function to query default distance measurement units for project.

dumpProperties

ellipsoid

Returns a proj string representing the project’s ellipsoid setting, e.g., “WGS84”.

entryList

Returns keys with values – do not return keys that contain other keys

error

Returns error message from previous read/write

evaluateDefaultValues

Should default values be evaluated on provider side when requested and not when committed.

fileInfo

Returns QFileInfo object for the project’s associated file.

fileName

Returns the project’s file name.

generateTsFile

Triggers the collection strings of .qgs to be included in ts file and calls writeTsFile()

homePath

Returns the project’s home path.

instance

Returns the QgsProject singleton instance

isDirty

Returns True if the project has been modified since the last write()

isSignalConnected

isZipped

Returns True if the project comes from a zip archive, False otherwise.

labelingEngineSettings

Returns project’s global labeling engine settings

lastModified

Returns last modified time of the project file as returned by the file system (or other project storage).

layerIsEmbedded

Returns project file path if layer is embedded from other project file.

layerStore

Returns a pointer to the project’s internal layer store.

layerTreeRegistryBridge

Returns pointer to the helper class that synchronizes map layer registry with layer tree

layerTreeRoot

Returns pointer to the root (invisible) node of the project’s layer tree

layoutManager

Returns the project’s layout manager, which manages compositions within the project.

mapLayer

Retrieve a pointer to a registered layer by layer ID.

mapLayers

Returns a map of all registered layers by layer ID.

mapLayersByName

Retrieve a list of matching registered layers by layer name.

mapLayersByShortName

Retrieves a list of matching registered layers by layer shortName.

mapThemeCollection

Returns pointer to the project’s map theme collection.

metadata

Returns a reference to the project’s metadata store.

nonIdentifiableLayers

Gets the list of layers which currently should not be taken into account on map identification

pathResolver

Returns path resolver object with considering whether the project uses absolute or relative paths and using current project’s path.

presetHomePath

Returns any manual project home path setting, or an empty string if not set.

projectStorage

Returns pointer to project storage implementation that handles read/write of the project file.

read

Reads given project file from the given file.

readBoolEntry

readDoubleEntry

readEntry

readLayer

Reads the layer described in the associated DOM node.

readListEntry

Key value accessors

readNumEntry

readPath

Turn filename read from the project file to an absolute path

receivers

registerTranslatableContainers

Registers the containers that require translation into the translationContext.

registerTranslatableObjects

Registers the objects that require translation into the translationContext.

relationManager

reloadAllLayers

Reload all registered layer’s provider data caches, synchronising the layer with any changes in the datasource.

removeAllMapLayers

Removes all registered layers.

removeEntry

Remove the given key

removeMapLayer

Remove a layer from the registry by layer ID.

removeMapLayers

Remove a set of layers from the registry by layer ID.

requiredLayers

Returns a set of map layers that are required in the project and therefore they should not get removed from the project.

sender

senderSignalIndex

setAreaUnits

Sets the default area measurement units for the project.

setAutoTransaction

Transactional editing means that on supported datasources (postgres databases) the edit state of all tables that originate from the same database are synchronized and executed in a server side transaction.

setAvoidIntersectionsLayers

A list of layers with which intersections should be avoided.

setBadLayerHandler

Change handler for missing layers.

setCrs

Sets the project’s native coordinate reference system.

setCustomVariables

A map of custom project variables.

setDirty

Flag the project as dirty (modified).

setDistanceUnits

Sets the default distance measurement units for the project.

setEllipsoid

Sets the project’s ellipsoid from a proj string representation, e.g., “WGS84”.

setEvaluateDefaultValues

Defines if default values should be evaluated on provider side when requested and not when committed.

setFileName

Sets the file name associated with the project.

setLabelingEngineSettings

Sets project’s global labeling engine settings

setMetadata

Sets the project’s metadata store.

setNonIdentifiableLayers

Set a list of layers which should not be taken into account on map identification

setPresetHomePath

Sets the project’s home path.

setProjectColors

Sets the colors for the project’s color scheme (see QgsProjectColorScheme).

setRequiredLayers

Configures a set of map layers that are required in the project and therefore they should not get removed from the project.

setSnappingConfig

The snapping configuration for this project.

setTitle

Sets the project’s title.

setTopologicalEditing

Convenience function to set topological editing

setTransformContext

Sets the project’s coordinate transform context, which stores various information regarding which datum transforms should be used when transforming points from a source to destination coordinate reference system.

setTrustLayerMetadata

Sets the trust option allowing to indicate if the extent has to be read from the XML document when data source has no metadata or if the data provider has to determine it.

snappingConfig

The snapping configuration for this project.

subkeyList

Returns keys with keys – do not return keys that contain only values

takeMapLayer

Takes a layer from the registry.

timerEvent

title

Returns the project’s title.

topologicalEditing

Convenience function to query topological editing status

transactionGroup

Returns the matching transaction group from a provider key and connection string.

transformContext

Returns a copy of the project’s coordinate transform context, which stores various information regarding which datum transforms should be used when transforming points from a source to destination coordinate reference system.

translate

Translates the project with QTranslator and qm file

trustLayerMetadata

Returns True if the trust option is activated, False otherwise.

validCount

Returns the number of registered valid layers.

write

Writes the project to a file.

writeEntry

Write an integer entry to the project file.

writeEntryBool

Write a boolean entry to the project file.

writeEntryDouble

Write a double entry to the project file.

writePath

Prepare a filename to save it to the project file.

Signals

avoidIntersectionsLayersChanged

Emitted whenever avoidIntersectionsLayers has changed.

cleared

Emitted when the project is cleared (and additionally when an open project is cleared just before a new project is read).

crsChanged

Emitted when the CRS of the project has changed.

customVariablesChanged

Emitted whenever the expression variables stored in the project have been changed.

ellipsoidChanged

Emitted when the project ellipsoid is changed.

fileNameChanged

Emitted when the file name of the project changes [signal]

homePathChanged

Emitted when the home path of the project changes.

isDirtyChanged

Emitted when the project dirty status changes.

labelingEngineSettingsChanged

Emitted when global configuration of the labeling engine changes.

layerLoaded

Emitted when a layer from a projects was read.

layerRemoved

Emitted after a layer was removed from the registry.

layerWasAdded

Emitted when a layer was added to the registry.

layerWillBeRemoved

Emitted when a layer is about to be removed from the registry.

layersAdded

Emitted when one or more layers were added to the registry.

layersRemoved

Emitted after one or more layers were removed from the registry.

layersWillBeRemoved

Emitted when one or more layers are about to be removed from the registry.

legendLayersAdded

Emitted, when a layer was added to the registry and the legend.

loadingLayer

Emitted when a layer is loaded [signal]

loadingLayerMessageReceived

Emitted when loading layers has produced some messages

mapThemeCollectionChanged

Emitted when the map theme collection changes.

metadataChanged

Emitted when the project’s metadata is changed.

missingDatumTransforms

Emitted when datum transforms stored in the project are not available locally.

nonIdentifiableLayersChanged

Emitted when the list of layer which are excluded from map identification changes

oldProjectVersionWarning

Emitted when an old project file is read.

projectColorsChanged

Emitted whenever the project’s color scheme has been changed.

projectSaved

Emitted when the project file has been written and closed.

readMapLayer

Emitted after the basic initialization of a layer from the project file is done.

readProject

Emitted when a project is being read.

readProjectWithContext

Emitted when a project is being read.

removeAll

Emitted when all layers are removed, before layersWillBeRemoved() and layerWillBeRemoved() signals are emitted.

snappingConfigChanged

Emitted whenever the configuration for snapping has changed.

topologicalEditingChanged

Emitted when the topological editing flag has changed.

transactionGroupsChanged

Emitted whenever a new transaction group has been created or a transaction group has been removed.

transformContextChanged

Emitted when the project transformContext() is changed.

writeMapLayer

Emitted when a layer is being saved.

writeProject

Emitted when the project is being written.

Attributes

FlagDontResolveLayers

FlagDontResolveLayers = 1
class ReadFlag

Bases: int

class ReadFlags

Bases: sip.wrapper

QgsProject.ReadFlags(Union[QgsProject.ReadFlags, QgsProject.ReadFlag]) QgsProject.ReadFlags(QgsProject.ReadFlags)

absoluteFilePath(self) → str

Returns full absolute path to the project file if the project is stored in a file system - derived from fileName(). Returns empty string when the project is stored in a project storage (there is no concept of paths for custom project storages).

New in version 3.2.

absolutePath(self) → str

Returns full absolute path to the project folder if the project is stored in a file system - derived from fileName(). Returns empty string when the project is stored in a project storage (there is no concept of paths for custom project storages).

New in version 3.2.

accept(self, visitor: QgsStyleEntityVisitorInterface) → bool

Accepts the specified style entity visitor, causing it to visit all style entities associated with the project.

Returns True if the visitor should continue visiting other objects, or False if visiting should be canceled.

New in version 3.10.

addMapLayer(self, mapLayer: QgsMapLayer, addToLegend: bool = True) → QgsMapLayer

Add a layer to the map of loaded layers.

The layersAdded() and layerWasAdded() signals will always be emitted. The legendLayersAdded() signal is emitted only if addToLegend is True. If you are adding multiple layers at once, you should use addMapLayers() instead.

Parameters
  • mapLayer – A layer to add to the registry

  • addToLegend – If True (by default), the layer will be added to the legend and to the main canvas. If you have a private layer you can set this parameter to False to hide it.

Returns

None if unable to add layer, otherwise pointer to newly added layer

See also

addMapLayers()

Note

As a side-effect QgsProject is made dirty.

Note

Use addMapLayers if adding more than one layer at a time

Note

takeOwnership is not available in the Python bindings - the registry will always take ownership

See also

addMapLayers()

addMapLayers(self, mapLayers: Iterable[QgsMapLayer], addToLegend: bool = True) → List[QgsMapLayer]

Add a list of layers to the map of loaded layers.

The layersAdded() and layerWasAdded() signals will always be emitted. The legendLayersAdded() signal is emitted only if addToLegend is True.

Parameters
  • mapLayers – A list of layer which should be added to the registry

  • addToLegend – If True (by default), the layers will be added to the legend and to the main canvas. If you have a private layer you can set this parameter to False to hide it.

Returns

a list of the map layers that were added successfully. If a layer or already exists in the registry, it will not be part of the returned QList.

Note

As a side-effect QgsProject is made dirty.

Note

takeOwnership is not available in the Python bindings - the registry will always take ownership

See also

addMapLayer()

New in version 1.8.

annotationManager(self) → QgsAnnotationManager

Returns pointer to the project’s annotation manager.

New in version 3.0.

areaUnits(self) → QgsUnitTypes.AreaUnit

Convenience function to query default area measurement units for project.

See also

distanceUnits()

New in version 2.14.

autoTransaction(self) → bool

Transactional editing means that on supported datasources (postgres databases) the edit state of all tables that originate from the same database are synchronized and executed in a server side transaction.

New in version 2.16.

auxiliaryStorage(self) → QgsAuxiliaryStorage

Returns the current auxiliary storage.

New in version 3.0.

avoidIntersectionsLayers(self) → List[QgsVectorLayer]

A list of layers with which intersections should be avoided.

New in version 3.0.

avoidIntersectionsLayersChanged

Emitted whenever avoidIntersectionsLayers has changed.

New in version 3.0: [signal]

baseName(self) → str

Returns the base name of the project file without the path and without extension - derived from fileName().

New in version 3.2.

blockDirtying

alias of qgis.core.additions.projectdirtyblocker.ProjectDirtyBlocker

childEvent()
clear(self)

Clears the project, removing all settings and resetting it back to an empty, default state.

See also

cleared()

New in version 2.4.

cleared

Emitted when the project is cleared (and additionally when an open project is cleared just before a new project is read).

See also

clear()

New in version 3.2: [signal]

connectNotify()
count(self) → int

Returns the number of registered layers.

createEmbeddedGroup(self, groupName: str, projectFilePath: str, invisibleLayers: Iterable[str], flags: Union[QgsProject.ReadFlags, QgsProject.ReadFlag] = 0) → QgsLayerTreeGroup

Create layer group instance defined in an arbitrary project file.

The optional flags argument can be used to control layer reading behavior.

New in version 2.4.

createExpressionContext(self) → QgsExpressionContext
crs(self) → QgsCoordinateReferenceSystem

Returns the project’s native coordinate reference system.

See also

setCrs()

See also

ellipsoid()

New in version 3.0.

crsChanged

Emitted when the CRS of the project has changed.

New in version 3.0: [signal]

customEvent()
customVariables(self) → Dict[str, Any]

A map of custom project variables. To get all available variables including generated ones use QgsExpressionContextUtils.projectScope() instead.

customVariablesChanged

Emitted whenever the expression variables stored in the project have been changed.

New in version 3.0: [signal]

defaultCrsForNewLayers(self) → QgsCoordinateReferenceSystem

Returns the default CRS for new layers based on the settings and the current project CRS

disconnectNotify()
distanceUnits(self) → QgsUnitTypes.DistanceUnit

Convenience function to query default distance measurement units for project.

See also

areaUnits()

New in version 2.14.

dumpProperties(self)
ellipsoid(self) → str

Returns a proj string representing the project’s ellipsoid setting, e.g., “WGS84”.

See also

setEllipsoid()

See also

crs()

New in version 3.0.

ellipsoidChanged

Emitted when the project ellipsoid is changed.

See also

setEllipsoid()

See also

ellipsoid()

New in version 3.0: [signal]

entryList(self, scope: str, key: str) → List[str]

Returns keys with values – do not return keys that contain other keys

Note

equivalent to QgsSettings entryList()

error(self) → str

Returns error message from previous read/write

evaluateDefaultValues(self) → bool

Should default values be evaluated on provider side when requested and not when committed.

New in version 2.16.

fileInfo(self) → QFileInfo

Returns QFileInfo object for the project’s associated file.

Note

The use of this method is discouraged since QGIS 3.2 as it only works with project files stored in the file system. It is recommended to use absoluteFilePath(), baseName(), lastModifiedTime() as replacements that are aware of the fact that projects may be saved in other project storages.

See also

fileName()

New in version 2.9.

Deprecated since version Use: absoluteFilePath(), baseName() or lastModifiedTime() instead

fileName(self) → str

Returns the project’s file name. This is the file or the storage URI which contains the project’s XML representation.

See also

setFileName()

See also

fileInfo()

fileNameChanged

Emitted when the file name of the project changes [signal]

generateTsFile(self, locale: str)

Triggers the collection strings of .qgs to be included in ts file and calls writeTsFile()

New in version 3.4.

homePath(self) → str

Returns the project’s home path. This will either be a manually set home path (see presetHomePath()) or the path containing the project file itself.

This method always returns the absolute path to the project’s home. See presetHomePath() to retrieve any manual project home path override (e.g. relative home paths).

See also

presetHomePath()

homePathChanged

Emitted when the home path of the project changes.

See also

homePath()

See also

presetHomePath() [signal]

instance() → QgsProject

Returns the QgsProject singleton instance

isDirty(self) → bool

Returns True if the project has been modified since the last write()

isDirtyChanged

Emitted when the project dirty status changes.

Parameters

dirtyTrue if the project is in a dirty state and has pending unsaved changes.

New in version 3.2: [signal]

isSignalConnected()
isZipped(self) → bool

Returns True if the project comes from a zip archive, False otherwise.

labelingEngineSettings(self) → QgsLabelingEngineSettings

Returns project’s global labeling engine settings

New in version 3.0.

labelingEngineSettingsChanged

Emitted when global configuration of the labeling engine changes.

New in version 3.0: [signal]

lastModified(self) → QDateTime

Returns last modified time of the project file as returned by the file system (or other project storage).

New in version 3.2.

layerIsEmbedded(self, id: str) → str

Returns project file path if layer is embedded from other project file. Returns empty string if layer is not embedded

layerLoaded

Emitted when a layer from a projects was read.

Parameters
  • i – current layer

  • n – number of layers [signal]

layerRemoved

Emitted after a layer was removed from the registry.

Parameters

layerId – The ID of the layer removed.

Note

Consider using layersRemoved() instead

See also

layerWillBeRemoved() [signal]

layerStore(self) → QgsMapLayerStore

Returns a pointer to the project’s internal layer store. /since QGIS 3.0

layerTreeRegistryBridge(self) → QgsLayerTreeRegistryBridge

Returns pointer to the helper class that synchronizes map layer registry with layer tree

New in version 2.4.

layerTreeRoot(self) → QgsLayerTree

Returns pointer to the root (invisible) node of the project’s layer tree

New in version 2.4.

layerWasAdded

Emitted when a layer was added to the registry.

Note

Consider using layersAdded() instead

See also

layersAdded() [signal]

layerWillBeRemoved

Emitted when a layer is about to be removed from the registry.

Parameters

layerId – The ID of the layer to be removed.

Note

Consider using layersWillBeRemoved() instead

See also

layerRemoved() [signal]

layerWillBeRemoved(self, layer: QgsMapLayer) Emitted when a layer is about to be removed from the registry.

Parameters

layer – The layer to be removed.

Note

Consider using layersWillBeRemoved() instead

See also

layerRemoved() [signal]

layersAdded

Emitted when one or more layers were added to the registry. This signal is also emitted for layers added to the registry, but not to the legend.

Parameters

layers – List of layers which have been added.

See also

layerWasAdded() [signal]

layersRemoved

Emitted after one or more layers were removed from the registry.

Parameters

layerIds – A list of IDs of the layers which were removed.

See also

layersWillBeRemoved() [signal]

layersWillBeRemoved

Emitted when one or more layers are about to be removed from the registry.

Parameters

layerIds – A list of IDs for the layers which are to be removed.

See also

layersRemoved() [signal]

layersWillBeRemoved(self, layers: Iterable[QgsMapLayer]) Emitted when one or more layers are about to be removed from the registry.

Parameters

layers – A list of layers which are to be removed.

See also

layersRemoved() [signal]

layoutManager(self) → QgsLayoutManager

Returns the project’s layout manager, which manages compositions within the project.

New in version 3.0.

legendLayersAdded

Emitted, when a layer was added to the registry and the legend. Layers can also be private layers, which are signalled by layersAdded() and layerWasAdded() but will not be advertised by this signal.

Parameters

layers – List of QgsMapLayer which were added to the legend. [signal]

loadingLayer

Emitted when a layer is loaded [signal]

loadingLayerMessageReceived

Emitted when loading layers has produced some messages

Parameters
  • layerName – the layer name

  • messages – a list of pairs of Qgis.MessageLevel and messages

New in version 3.2: [signal]

mapLayer(self, layerId: str) → QgsMapLayer

Retrieve a pointer to a registered layer by layer ID.

Parameters

layerId – ID of layer to retrieve

Returns

matching layer, or None if no matching layer found

See also

mapLayers()

mapLayers(self, validOnly: bool = False) → object

Returns a map of all registered layers by layer ID.

Parameters

validOnly – if set only valid layers will be returned

See also

mapLayer()

See also

layers()

mapLayersByName(self, layerName: str) → List[QgsMapLayer]

Retrieve a list of matching registered layers by layer name.

Parameters

layerName – name of layers to match

Returns

list of matching layers

See also

mapLayer()

See also

mapLayers()

mapLayersByShortName(self, shortName: str) → List[QgsMapLayer]

Retrieves a list of matching registered layers by layer shortName. If layer’s short name is empty a match with layer’s name is attempted.

Returns

list of matching layers

See also

mapLayer()

See also

mapLayers()

New in version 3.10.

mapThemeCollection(self) → QgsMapThemeCollection

Returns pointer to the project’s map theme collection.

Note

renamed in QGIS 3.0, formerly QgsVisibilityPresetCollection

New in version 2.12.

mapThemeCollectionChanged

Emitted when the map theme collection changes. This only happens when the map theme collection is reset. Any pointer previously received from mapThemeCollection() must no longer be used after this signal is emitted. You must still connect to signals from the map theme collection if you want to be notified about new map themes being added and map themes being removed.

New in version 3.0: [signal]

metadata(self) → QgsProjectMetadata

Returns a reference to the project’s metadata store.

See also

setMetadata()

New in version 3.2.

metadataChanged

Emitted when the project’s metadata is changed.

See also

setMetadata()

See also

metadata()

New in version 3.2: [signal]

missingDatumTransforms

Emitted when datum transforms stored in the project are not available locally.

New in version 3.0: [signal]

nonIdentifiableLayers(self) → List[str]

Gets the list of layers which currently should not be taken into account on map identification

Deprecated since version since: QGIS 3.4 use QgsMapLayer.setFlags() instead

nonIdentifiableLayersChanged

Emitted when the list of layer which are excluded from map identification changes

Deprecated since version since: QGIS 3.4 [signal]

oldProjectVersionWarning

Emitted when an old project file is read. [signal]

pathResolver(self) → QgsPathResolver

Returns path resolver object with considering whether the project uses absolute or relative paths and using current project’s path.

New in version 3.0.

presetHomePath(self) → str

Returns any manual project home path setting, or an empty string if not set.

This path may be a relative path. See homePath() to retrieve a path which is always an absolute path.

See also

homePath()

New in version 3.2.

projectColorsChanged

Emitted whenever the project’s color scheme has been changed.

New in version 3.6: [signal]

projectSaved

Emitted when the project file has been written and closed. [signal]

projectStorage(self) → QgsProjectStorage

Returns pointer to project storage implementation that handles read/write of the project file. If the project file is stored in the local file system, returns None. The project storage object is inferred from fileName() of the project.

New in version 3.2.

read(self, filename: str, flags: Union[QgsProject.ReadFlags, QgsProject.ReadFlag] = 0) → bool

Reads given project file from the given file.

Parameters
  • filename – name of project file to read

  • flags – optional flags which control the read behavior of projects

Returns

True if project file has been read successfully

read(self, flags: Union[QgsProject.ReadFlags, QgsProject.ReadFlag] = 0) -> bool Reads the project from its currently associated file (see fileName() ).

The flags argument can be used to specify optional flags which control the read behavior of projects.

Returns

True if project file has been read successfully

readBoolEntry(self, scope: str, key: str, def_: bool = False) → Tuple[bool, bool]
readDoubleEntry(self, scope: str, key: str, def_: float = 0) → Tuple[float, bool]
readEntry(self, scope: str, key: str, def_: str = '') → Tuple[str, bool]
readLayer(self, layerNode: QDomNode) → bool

Reads the layer described in the associated DOM node.

Note

This method is mainly for use by QgsProjectBadLayerHandler subclasses that may fix definition of bad layers with the user’s help in GUI. Calling this method with corrected DOM node adds the layer back to the project.

Parameters

layerNode – represents a QgsProject DOM node that encodes a specific layer.

readListEntry(self, scope: str, key: str, def_: Iterable[str] = []) → Tuple[List[str], bool]

Key value accessors

keys would be the familiar QgsSettings-like ‘/’ delimited entries, implying a hierarchy of keys and corresponding values

readMapLayer

Emitted after the basic initialization of a layer from the project file is done. You can use this signal to read additional information from the project file.

Parameters
  • mapLayer – The map layer which is being initialized

  • layerNode – The layer node from the project file [signal]

readNumEntry(self, scope: str, key: str, def_: int = 0) → Tuple[int, bool]
readPath(self, filename: str) → str

Turn filename read from the project file to an absolute path

readProject

Emitted when a project is being read. [signal]

readProjectWithContext

Emitted when a project is being read. And passing the /a context [signal]

receivers()
registerTranslatableContainers(self, translationContext: QgsTranslationContext, parent: QgsAttributeEditorContainer, layerId: str)

Registers the containers that require translation into the translationContext. This is a recursive function to get all the child containers.

Parameters
  • translationContext – where the objects will be registered

  • parent – parent-container containing list of children

  • layerId – to store under the correct context

New in version 3.4.

registerTranslatableObjects(self, translationContext: QgsTranslationContext)

Registers the objects that require translation into the translationContext. So there can be created a ts file with these values.

New in version 3.4.

relationManager(self) → QgsRelationManager
reloadAllLayers(self)

Reload all registered layer’s provider data caches, synchronising the layer with any changes in the datasource.

removeAll

Emitted when all layers are removed, before layersWillBeRemoved() and layerWillBeRemoved() signals are emitted. The layersWillBeRemoved() and layerWillBeRemoved() signals will still be emitted following this signal. You can use this signal to do easy (and fast) cleanup. [signal]

removeAllMapLayers(self)

Removes all registered layers. If the registry has ownership of any layers these layers will also be deleted.

Note

As a side-effect the QgsProject instance is marked dirty.

Note

Calling this method will cause the removeAll() signal to be emitted.

See also

removeMapLayer()

removeEntry(self, scope: str, key: str) → bool

Remove the given key

removeMapLayer(self, layerId: str)

Remove a layer from the registry by layer ID.

The specified layer will be removed from the registry. If the registry has ownership of the layer then it will also be deleted.

Parameters

layerId – ID of the layer to remove

Note

As a side-effect the QgsProject instance is marked dirty.

removeMapLayer(self, layer: QgsMapLayer) Remove a layer from the registry.

The specified layer will be removed from the registry. If the registry has ownership of the layer then it will also be deleted.

Parameters

layer – The layer to remove. None values are ignored.

Note

As a side-effect the QgsProject instance is marked dirty.

removeMapLayers(self, layerIds: Iterable[str])

Remove a set of layers from the registry by layer ID.

The specified layers will be removed from the registry. If the registry has ownership of any layers these layers will also be deleted.

Parameters

layerIds – list of IDs of the layers to remove

Note

As a side-effect the QgsProject instance is marked dirty.

See also

removeMapLayer()

New in version 1.8.

removeMapLayers(self, layers: Iterable[QgsMapLayer]) Remove a set of layers from the registry.

The specified layers will be removed from the registry. If the registry has ownership of any layers these layers will also be deleted.

Parameters

layers – A list of layers to remove. None values are ignored.

Note

As a side-effect the QgsProject instance is marked dirty.

See also

removeMapLayer()

requiredLayers(self) → Set[QgsMapLayer]

Returns a set of map layers that are required in the project and therefore they should not get removed from the project. The set of layers may be configured by users in project properties. and it is mainly a hint for the user interface to protect users from removing layers that important in the project. The removeMapLayer(), removeMapLayers() calls do not block removal of layers listed here.

Deprecated since version since: QGIS 3.4 use QgsMapLayer.flags() instead

New in version 3.2.

sender()
senderSignalIndex()
setAreaUnits(self, unit: QgsUnitTypes.AreaUnit)

Sets the default area measurement units for the project.

See also

areaUnits()

New in version 3.0.

setAutoTransaction(self, autoTransaction: bool)

Transactional editing means that on supported datasources (postgres databases) the edit state of all tables that originate from the same database are synchronized and executed in a server side transaction.

Make sure that this is only called when all layers are not in edit mode.

New in version 2.16.

setAvoidIntersectionsLayers(self, layers: Iterable[QgsVectorLayer])

A list of layers with which intersections should be avoided.

New in version 3.0.

setBadLayerHandler(self, handler: QgsProjectBadLayerHandler)

Change handler for missing layers. Deletes old handler and takes ownership of the new one.

setCrs(self, crs: QgsCoordinateReferenceSystem, adjustEllipsoid: bool = False)

Sets the project’s native coordinate reference system. If adjustEllipsoid is set to True, the ellpsoid of this project will be set to the ellipsoid imposed by the CRS.

See also

crs()

See also

setEllipsoid()

New in version 3.0.

setCustomVariables(self, customVariables: Dict[str, Any])

A map of custom project variables. Be careful not to set generated variables.

setDirty(self, b: bool = True)

Flag the project as dirty (modified). If this flag is set, the user will be asked to save changes to the project before closing the current project.

Note

promoted to public slot in 2.16

New in version 2.4.

setDistanceUnits(self, unit: QgsUnitTypes.DistanceUnit)

Sets the default distance measurement units for the project.

See also

distanceUnits()

See also

setAreaUnits()

New in version 3.0.

setEllipsoid(self, ellipsoid: str)

Sets the project’s ellipsoid from a proj string representation, e.g., “WGS84”.

See also

ellipsoid()

See also

setCrs()

New in version 3.0.

setEvaluateDefaultValues(self, evaluateDefaultValues: bool)

Defines if default values should be evaluated on provider side when requested and not when committed.

New in version 2.16.

setFileName(self, name: str)

Sets the file name associated with the project. This is the file or the storage URI which contains the project’s XML representation.

Parameters

name – project file name

See also

fileName()

setLabelingEngineSettings(self, settings: QgsLabelingEngineSettings)

Sets project’s global labeling engine settings

New in version 3.0.

setMetadata(self, metadata: QgsProjectMetadata)

Sets the project’s metadata store.

See also

metadata()

New in version 3.2.

setNonIdentifiableLayers(self, layers: Iterable[QgsMapLayer])

Set a list of layers which should not be taken into account on map identification

Deprecated since version since: QGIS 3.4 use QgsMapLayer.setFlags() instead

setNonIdentifiableLayers(self, layerIds: Iterable[str]) Set a list of layers which should not be taken into account on map identification

Deprecated since version since: QGIS 3.4 use QgsMapLayer.setFlags() instead

setPresetHomePath(self, path: str)

Sets the project’s home path. If an empty path is specified than the home path will be automatically determined from the project’s file path.

See also

presetHomePath()

See also

homePath()

New in version 3.2.

setProjectColors(self, colors: Iterable[Tuple[Union[QColor, Qt.GlobalColor], str]])

Sets the colors for the project’s color scheme (see QgsProjectColorScheme).

New in version 3.6.

setRequiredLayers(self, layers: Iterable[QgsMapLayer])

Configures a set of map layers that are required in the project and therefore they should not get removed from the project. The set of layers may be configured by users in project properties. and it is mainly a hint for the user interface to protect users from removing layers that important in the project. The removeMapLayer(), removeMapLayers() calls do not block removal of layers listed here.

Deprecated since version since: QGIS 3.4 use QgsMapLayer.setFlags() instead

New in version 3.2.

setSnappingConfig(self, snappingConfig: QgsSnappingConfig)

The snapping configuration for this project.

New in version 3.0.

setTitle(self, title: str)

Sets the project’s title.

Parameters

title – new title

Note

Since QGIS 3.2 this is just a shortcut to setting the title in the project’s metadata().

See also

title()

New in version 2.4.

setTopologicalEditing(self, enabled: bool)

Convenience function to set topological editing

setTransformContext(self, context: QgsCoordinateTransformContext)

Sets the project’s coordinate transform context, which stores various information regarding which datum transforms should be used when transforming points from a source to destination coordinate reference system.

New in version 3.0.

setTrustLayerMetadata(self, trust: bool)

Sets the trust option allowing to indicate if the extent has to be read from the XML document when data source has no metadata or if the data provider has to determine it. Moreover, when this option is activated, primary key unicity is not checked for views and materialized views with Postgres provider.

Parameters

trustTrue to trust the project, False otherwise

New in version 3.0.

snappingConfig(self) → QgsSnappingConfig

The snapping configuration for this project.

New in version 3.0.

snappingConfigChanged

Emitted whenever the configuration for snapping has changed. [signal]

subkeyList(self, scope: str, key: str) → List[str]

Returns keys with keys – do not return keys that contain only values

Note

equivalent to QgsSettings subkeyList()

takeMapLayer(self, layer: QgsMapLayer) → QgsMapLayer

Takes a layer from the registry. If the layer was owned by the project, the layer will be returned without deleting it. The caller takes ownership of the layer and is responsible for deleting it.

See also

removeMapLayer()

New in version 3.0.

timerEvent()
title(self) → str

Returns the project’s title.

See also

setTitle()

Note

Since QGIS 3.2 this is just a shortcut to retrieving the title from the project’s metadata().

topologicalEditing(self) → bool

Convenience function to query topological editing status

topologicalEditingChanged

Emitted when the topological editing flag has changed.

New in version 3.0: [signal]

transactionGroup(self, providerKey: str, connString: str) → QgsTransactionGroup

Returns the matching transaction group from a provider key and connection string.

Returns None if a matching transaction group is not available.

New in version 3.2.

transactionGroupsChanged

Emitted whenever a new transaction group has been created or a transaction group has been removed.

New in version 3.0: [signal]

transformContext(self) → QgsCoordinateTransformContext

Returns a copy of the project’s coordinate transform context, which stores various information regarding which datum transforms should be used when transforming points from a source to destination coordinate reference system.

New in version 3.0.

transformContextChanged

Emitted when the project transformContext() is changed.

New in version 3.0: [signal]

translate(self, context: str, sourceText: str, disambiguation: str = None, n: int = -1) → str

Translates the project with QTranslator and qm file

Returns

the result string (in case there is no QTranslator loaded the sourceText)

Parameters
  • context – describing layer etc.

  • sourceText – is the identifier of this text

  • disambiguation – it’s the disambiguation

  • n – if -1 uses the appropriate form

New in version 3.4.

trustLayerMetadata(self) → bool

Returns True if the trust option is activated, False otherwise. This option allows indicateing if the extent has to be read from the XML document when data source has no metadata or if the data provider has to determine it. Moreover, when this option is activated, primary key unicity is not checked for views and materialized views with Postgres provider.

New in version 3.0.

validCount(self) → int

Returns the number of registered valid layers.

write(self, filename: str) → bool

Writes the project to a file.

Parameters

filename – destination file

Returns

True if project was written successfully

Note

calling this implicitly sets the project’s filename (see setFileName() )

Note

isDirty() will be set to False if project is successfully written

New in version 3.0.

write(self) -> bool Writes the project to its current associated file (see fileName() ).

Returns

True if project was written successfully

Note

isDirty() will be set to False if project is successfully written

writeEntry(self, scope: str, key: str, value: int) → bool

Write an integer entry to the project file.

Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values

Note

The key string must be valid xml tag names in order to be saved to the file.

writeEntry(self, scope: str, key: str, value: str) -> bool Write a string entry to the project file.

Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values

Note

The key string must be valid xml tag names in order to be saved to the file.

writeEntry(self, scope: str, key: str, value: Iterable[str]) -> bool Write a string list entry to the project file.

Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values

Note

The key string must be valid xml tag names in order to be saved to the file.

writeEntryBool(self, scope: str, key: str, value: bool) → bool

Write a boolean entry to the project file.

Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values

Note

The key string must be valid xml tag names in order to be saved to the file.

Note

available in Python bindings as writeEntryBool

writeEntryDouble(self, scope: str, key: str, value: float) → bool

Write a double entry to the project file.

Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values

Note

The key string must be valid xml tag names in order to be saved to the file.

Note

available in Python bindings as writeEntryDouble

writeMapLayer

Emitted when a layer is being saved. You can use this method to save additional information to the layer.

Parameters
  • mapLayer – The map layer which is being initialized

  • layerElem – The layer element from the project file

  • doc – The document [signal]

writePath(self, filename: str) → str

Prepare a filename to save it to the project file. Creates an absolute or relative path according to the project settings. Paths written to the project file should be prepared with this method.

writeProject

Emitted when the project is being written. [signal]