Class: QgsProject

Encapsulates a QGIS project, including sets of map layers and their styles, layouts, annotations, canvases, etc.

QgsProject is available both as a singleton (QgsProject.instance()) and for use as standalone objects. The QGIS project singleton always gives access to the canonical project reference open within the main QGIS application.

Note

QgsProject has two general kinds of state to make persistent. (I.e., to read and write.) First, QGIS proprietary information. Second plugin information.

Class Hierarchy

Inheritance diagram of qgis.core.QgsProject

Base classes

QObject

QgsExpressionContextGenerator

Abstract interface for generating an expression context.

QgsExpressionContextScopeGenerator

Abstract interface for generating an expression context scope.

QgsProjectTranslator

An interface for objects which can translate project strings.

Enums

AvoidIntersectionsMode

Flags which control how intersections of pre-existing feature are handled when digitizing new features.

DataDefinedServerProperty

Data defined properties.

FileFormat

alias of ProjectFileFormat

ReadFlag

alias of ProjectReadFlag

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.

attachedFiles

Returns a map of all attached files with identifier and real paths.

attachmentIdentifier

Returns an identifier for an attachment file path An attachment identifier is a string which does not depend on the project archive storage location.

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.

avoidIntersectionsMode

Returns the current avoid intersections mode.

backgroundColor

Returns the default background color used by default map canvases.

baseName

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

bookmarkManager

Returns the project's bookmark manager, which manages bookmarks within the project.

capabilities

Returns the project's capabilities, which dictate optional functionality which can be selectively enabled for a QgsProject object.

clear

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

commitChanges

Attempts to commit to the underlying data provider any buffered changes made since the last to call to startEditing().

count

Returns the number of registered layers.

createAttachedFile

Attaches a file to the project

createEmbeddedGroup

Create layer group instance defined in an arbitrary project file.

crs

Returns the project's native coordinate reference system.

crs3D

Returns the CRS to use for the project when transforming 3D data, or when z/elevation value handling is important.

customVariables

A map of custom project variables.

dataDefinedServerProperties

Returns the data defined properties used for overrides in user defined server parameters

defaultCrsForNewLayers

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

displaySettings

Returns the project's display settings, which contains settings and properties relating to how a QgsProject should display values such as map coordinates and bearings.

distanceUnits

Convenience function to query default distance measurement units for project.

dumpProperties

Dump out current project properties to stderr

editBufferGroup

Returns the edit buffer group

elevationProperties

Returns the project's elevation properties, which contains the project's elevation related settings.

elevationShadingRenderer

Returns the elevation shading renderer used for map shading

ellipsoid

Returns a proj string representing the project's ellipsoid setting, e.g., "WGS84".

entryList

Returns a list of child keys with values which exist within the the specified scope and key.

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.

filePathStorage

Returns the type of paths used when storing file paths in a QGS/QGZ project file.

flags

Returns the project's flags, which dictate the behavior of the project.

generateTsFile

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

gpsSettings

Returns the project's GPS settings, which contains settings and properties relating to how a QgsProject should interact with a GPS device.

homePath

Returns the project's home path.

isDirty

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

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).

lastSaveDateTime

Returns the date and time when the project was last saved.

lastSaveVersion

Returns the QGIS version which the project was last saved using.

layerIsEmbedded

Returns the source project file path if the layer with matching id 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 print layouts, atlases and reports within the project.

mainAnnotationLayer

Returns the main annotation layer associated with 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.

mapScales

Returns the list of custom project map scales.

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

originalPath

Returns the original path associated with the project.

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

Reads a boolean from the specified scope and key.

readDoubleEntry

Reads a double from the specified scope and key.

readEntry

Reads a string from the specified scope and key.

readLayer

Reads the layer described in the associated DOM node.

readListEntry

Reads a string list from the specified scope and key.

readNumEntry

Reads an integer from the specified scope and key.

readPath

Transforms a filename read from the project file to an absolute path.

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.

removeAttachedFile

Removes the attached file

removeEntry

Remove the given key from the specified scope.

removeMapLayer

Remove a layer from the registry by layer ID.

removeMapLayers

Remove a set of layers from the registry.

requiredLayers

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

resolveAttachmentIdentifier

Resolves an attachment identifier to a attachment file path

rollBack

Stops a current editing operation on vectorLayer and discards any uncommitted edits.

saveUser

Returns the user name that did the last save.

saveUserFullName

Returns the full user name that did the last save.

scaleMethod

Returns the method to use for map scale calculations for the project.

selectionColor

Returns the color used to highlight selected features

sensorManager

Returns the project's sensor manager, which manages sensors within the project.

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

Sets the list of layers with which intersections should be avoided.

setAvoidIntersectionsMode

Sets the avoid intersections mode.

setBackgroundColor

Sets the default background color used by default map canvases.

setBadLayerHandler

Change handler for missing layers.

setCrs

Sets the project's native coordinate reference system.

setCustomVariables

A map of custom project variables.

setDataDefinedServerProperties

Sets the data defined properties used for overrides in user defined server parameters to properties

setDirty

Flag the project as dirty (modified).

setDistanceUnits

Sets the default distance measurement units for the project.

setElevationShadingRenderer

Sets the elevation shading renderer used for global map shading

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.

setFilePathStorage

Sets the type of paths used when storing file paths in a QGS/QGZ project file.

setFlag

Sets whether a project flag is enabled.

setFlags

Sets the project's flags, which dictate the behavior of the project.

setLabelingEngineSettings

Sets project's global labeling engine settings

setMapScales

Sets the list of custom project map scales.

setMetadata

Sets the project's metadata store.

setNonIdentifiableLayers

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

setOriginalPath

Sets the original path associated with the project.

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.

setScaleMethod

Sets the method to use for map scale calculations for the project.

setSelectionColor

Sets the color used to highlight selected features.

setSnappingConfig

The snapping configuration for this project.

setTitle

Sets the project's title.

setTopologicalEditing

Convenience function to set topological editing

setTransactionMode

Set transaction mode

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.

setUseProjectScales

Sets whether project mapScales() are enabled.

setVerticalCrs

Sets the project's vertical coordinate reference system.

snappingConfig

The snapping configuration for this project.

startEditing

Makes the layer editable.

styleSettings

Returns the project's style settings, which contains settings and properties relating to how a QgsProject should handle styling.

subkeyList

Returns a list of child keys which contain other keys that exist within the the specified scope and key.

takeMapLayer

Takes a layer from the registry.

timeSettings

Returns the project's time settings, which contains the project's temporal range and other time based settings.

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.

transactionMode

Returns the transaction mode

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.

trustLayerMetadata

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

useProjectScales

Returns True if project mapScales() are enabled.

validCount

Returns the number of registered valid layers.

verticalCrs

Returns the project's vertical coordinate reference system.

viewSettings

Returns the project's view settings, which contains settings and properties relating to how a QgsProject should be viewed and behave inside a map canvas (e.g. map scales and default view extent).

viewsManager

Returns the project's views manager, which manages map views (including 3d maps) in the project.

write

Writes the project to a file.

writeEntry

Write an integer value to the project file.

writeEntryBool

Write a boolean value to the project file.

writeEntryDouble

Write a double value to the project file.

writePath

Prepare a filename to save it to the project file.

Static Methods

instance

Returns the QgsProject singleton instance

setInstance

Set the current project singleton instance to project

Signals

aboutToBeCleared

Emitted when the project is about to be cleared.

areaUnitsChanged

Emitted when the default area units changes.

avoidIntersectionsLayersChanged

Emitted whenever avoidIntersectionsLayers has changed.

avoidIntersectionsModeChanged

Emitted whenever the avoid intersections mode has changed.

backgroundColorChanged

Emitted whenever the project's canvas background color has been changed.

cleared

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

crs3DChanged

Emitted when the crs3D() of the project has changed.

crsChanged

Emitted when the crs() of the project has changed.

customVariablesChanged

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

dirtySet

Emitted when setDirty(true) is called.

distanceUnitsChanged

Emitted when the default distance units changes.

elevationShadingRendererChanged

Emitted when the map shading renderer changes

ellipsoidChanged

Emitted when the project ellipsoid is changed.

fileNameChanged

Emitted when the file name of the project changes

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

loadingLayerMessageReceived

Emitted when loading layers has produced some messages

mapScalesChanged

Emitted when the list of custom project map scales changes.

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.

readVersionMismatchOccurred

Emitted when a project is read and the version of QGIS used to save the project differs from the current QGIS version.

removeAll

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

scaleMethodChanged

Emitted when the project's scale method is changed.

selectionColorChanged

Emitted whenever the project's selection color has been changed.

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.

transactionModeChanged

Emitted when the transaction mode has changed.

transformContextChanged

Emitted when the project transformContext() is changed.

verticalCrsChanged

Emitted when the verticalCrs() of the project has changed.

writeMapLayer

Emitted when a layer is being saved.

writeProject

Emitted when the project is being written.

class qgis.core.QgsProject[source]

Bases: QObject, QgsExpressionContextGenerator, QgsExpressionContextScopeGenerator, QgsProjectTranslator

__init__(parent: QObject | None = None, capabilities: Qgis.ProjectCapabilities | Qgis.ProjectCapability = Qgis.ProjectCapability.ProjectStyles)

Create a new QgsProject.

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

Since QGIS 3.26.1 the capabilities argument specifies optional capabilities which can be selectively enabled for the project. These affect the QgsProject object for its entire lifetime.

Parameters:
class AvoidIntersectionsMode(*values)

Bases: IntEnum

Flags which control how intersections of pre-existing feature are handled when digitizing new features.

Note

Prior to QGIS 3.26 this was available as QgsProject.AvoidIntersectionsMode

Added in version 3.26.

  • AllowIntersections: Overlap with any feature allowed when digitizing new features

  • AvoidIntersectionsCurrentLayer: Overlap with features from the active layer when digitizing new features not allowed

  • AvoidIntersectionsLayers: Overlap with features from a specified list of layers when digitizing new features not allowed

class DataDefinedServerProperty(*values)

Bases: IntEnum

Data defined properties. Overrides of user defined server parameters are stored in a property collection and they can be retrieved using the indexes specified in this enum.

Added in version 3.14.

  • NoProperty: No property

  • AllProperties: All properties for item

  • WMSOnlineResource: Alias

FileFormat

alias of ProjectFileFormat

ReadFlag

alias of ProjectReadFlag

ReadFlags

alias of ProjectReadFlags

signal aboutToBeCleared[source]

Emitted when the project is about to be cleared.

See also

clear()

Added in version 3.34.

absoluteFilePath(self) str[source]

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).

Added in version 3.2.

Return type:

str

absolutePath(self) str[source]

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).

Added in version 3.2.

Return type:

str

accept(self, visitor: QgsStyleEntityVisitorInterface | None) bool[source]

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.

Added in version 3.10.

Parameters:

visitor (Optional[QgsStyleEntityVisitorInterface])

Return type:

bool

addMapLayer(self, mapLayer: QgsMapLayer | None, addToLegend: bool = True) QgsMapLayer | None[source]

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 (Optional[QgsMapLayer]) – A layer to add to the registry

  • addToLegend (bool = True) – 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.

Return type:

Optional[QgsMapLayer]

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 (Iterable[QgsMapLayer]) – A list of layer which should be added to the registry

  • addToLegend (bool = True) – 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.

Return type:

List[QgsMapLayer]

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()

annotationManager(self) QgsAnnotationManager | None[source]

Returns pointer to the project’s annotation manager.

Return type:

Optional[QgsAnnotationManager]

areaUnits(self) Qgis.AreaUnit[source]

Convenience function to query default area measurement units for project.

See also

distanceUnits()

Return type:

Qgis.AreaUnit

signal areaUnitsChanged[source]

Emitted when the default area units changes.

See also

setAreaUnits()

Added in version 3.28.

attachedFiles(self) List[str][source]

Returns a map of all attached files with identifier and real paths.

Added in version 3.22.

Return type:

List[str]

attachmentIdentifier(self, attachedFile: str | None) str[source]

Returns an identifier for an attachment file path An attachment identifier is a string which does not depend on the project archive storage location.

Parameters:

attachedFile (Optional[str]) – An attachment file path

Return type:

str

Returns:

An identifier for the attached file

Added in version 3.22.

autoTransaction(self) bool[source]

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.

Deprecated since version 3.26: Use transactionMode() instead.

Return type:

bool

auxiliaryStorage(self) QgsAuxiliaryStorage | None[source]

Returns the current auxiliary storage.

Return type:

Optional[QgsAuxiliaryStorage]

avoidIntersectionsLayers(self) List[QgsVectorLayer]

A list of layers with which intersections should be avoided.

Return type:

List[QgsVectorLayer]

signal avoidIntersectionsLayersChanged[source]

Emitted whenever avoidIntersectionsLayers has changed.

avoidIntersectionsMode(self) Qgis.AvoidIntersectionsMode[source]

Returns the current avoid intersections mode.

Added in version 3.14.

Return type:

Qgis.AvoidIntersectionsMode

signal avoidIntersectionsModeChanged[source]

Emitted whenever the avoid intersections mode has changed.

Added in version 3.14.

backgroundColor(self) QColor[source]

Returns the default background color used by default map canvases.

Added in version 3.10.

Return type:

QColor

signal backgroundColorChanged[source]

Emitted whenever the project’s canvas background color has been changed.

Added in version 3.10.

baseName(self) str[source]

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

Added in version 3.2.

Return type:

str

blockDirtying

alias of ProjectDirtyBlocker

bookmarkManager(self) QgsBookmarkManager | None[source]

Returns the project’s bookmark manager, which manages bookmarks within the project.

Added in version 3.10.

Return type:

Optional[QgsBookmarkManager]

capabilities(self) Qgis.ProjectCapabilities[source]

Returns the project’s capabilities, which dictate optional functionality which can be selectively enabled for a QgsProject object.

Added in version 3.26.1.

Return type:

Qgis.ProjectCapabilities

clear(self)[source]

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

See also

cleared()

signal cleared[source]

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

See also

clear()

Added in version 3.2.

commitChanges(self, stopEditing: bool = True, vectorLayer: QgsVectorLayer | None = None)[source]

Attempts to commit to the underlying data provider any buffered changes made since the last to call to startEditing().

Returns the result of the attempt. If a commit fails (i.e. False is returned), the in-memory changes are left untouched and are not discarded. This allows editing to continue if the commit failed on e.g. a disallowed value in a Postgres database - the user can re-edit and try again.

The commits occur in distinct stages, (add attributes, add features, change attribute values, change geometries, delete features, delete attributes) so if a stage fails, it can be difficult to roll back cleanly. Therefore any error message returned by commitErrors also includes which stage failed so that the user has some chance of repairing the damage cleanly.

Parameters:
  • stopEditing (bool = True) – if set to False, the layer will stay in editing mode. Otherwise the layer editing mode will be disabled if the commit is successful.

  • vectorLayer (Optional[QgsVectorLayer] = None) -> (bool) – for which the changes will be committed. For buffered transactions this parameter is not mandatory, as the changes from all layers will be committed.

Returns:

  • True if the commit was successful.

  • commitErrors: a list of descriptive errors if the commit fails.

See also

startEditing()

See also

rollBack()

Added in version 3.26.

count(self) int[source]

Returns the number of registered layers.

Return type:

int

createAttachedFile(self, nameTemplate: str | None) str[source]

Attaches a file to the project

Parameters:

nameTemplate (Optional[str]) – Any filename template, used as a basename for attachment file, i.e. “myfile.ext”

Return type:

str

Returns:

The path to the file where the contents can be written to.

Note

If the attachment file is used as a source for a project layer, the attachment will be removed automatically when the layer is deleted.

Added in version 3.22.

createEmbeddedGroup(self, groupName: str | None, projectFilePath: str | None, invisibleLayers: Iterable[str | None], flags: Qgis.ProjectReadFlags | Qgis.ProjectReadFlag = Qgis.ProjectReadFlags()) QgsLayerTreeGroup | None[source]

Create layer group instance defined in an arbitrary project file.

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

Parameters:
Return type:

Optional[QgsLayerTreeGroup]

crs(self) QgsCoordinateReferenceSystem[source]

Returns the project’s native coordinate reference system.

Warning

Since QGIS 3.38, consider using crs3D() whenever transforming 3D data or whenever z/elevation value handling is important.

See also

setCrs()

See also

crs3D()

See also

verticalCrs()

See also

ellipsoid()

See also

crsChanged()

Return type:

QgsCoordinateReferenceSystem

crs3D(self) QgsCoordinateReferenceSystem[source]

Returns the CRS to use for the project when transforming 3D data, or when z/elevation value handling is important.

The returned CRS will take into account verticalCrs() when appropriate, e.g. it may return a compound CRS consisting of crs() + verticalCrs(). This method may still return a 2D CRS, e.g in the case that crs() is a 2D CRS and no verticalCrs() has been set for the project. Check QgsCoordinateReferenceSystem.type() on the returned value to determine the type of CRS returned by this method.

Warning

It is NOT guaranteed that the returned CRS will actually be a 3D CRS, but rather it is guaranteed that the returned CRS is ALWAYS the most appropriate CRS to use when handling 3D data.

See also

crs()

See also

verticalCrs()

See also

crs3DChanged()

Added in version 3.38.

Return type:

QgsCoordinateReferenceSystem

signal crs3DChanged[source]

Emitted when the crs3D() of the project has changed.

See also

crs3D()

See also

crsChanged()

Added in version 3.38.

signal crsChanged[source]

Emitted when the crs() of the project has changed.

See also

crs()

See also

setCrs()

customVariables(self) Dict[str, Any][source]

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

Return type:

Dict[str, Any]

signal customVariablesChanged[source]

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

dataDefinedServerProperties(self) QgsPropertyCollection[source]

Returns the data defined properties used for overrides in user defined server parameters

Added in version 3.14.

Return type:

QgsPropertyCollection

defaultCrsForNewLayers(self) QgsCoordinateReferenceSystem[source]

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

Return type:

QgsCoordinateReferenceSystem

signal dirtySet[source]

Emitted when setDirty(true) is called.

Note

As opposed to isDirtyChanged(), this signal is invoked every time setDirty(true) is called, regardless of whether the project was already dirty.

Added in version 3.20.

displaySettings(self) QgsProjectDisplaySettings | None[source]

Returns the project’s display settings, which contains settings and properties relating to how a QgsProject should display values such as map coordinates and bearings.

Added in version 3.12.

Return type:

Optional[QgsProjectDisplaySettings]

distanceUnits(self) Qgis.DistanceUnit[source]

Convenience function to query default distance measurement units for project.

See also

areaUnits()

Return type:

Qgis.DistanceUnit

signal distanceUnitsChanged[source]

Emitted when the default distance units changes.

Added in version 3.28.

dumpProperties(self)[source]

Dump out current project properties to stderr

editBufferGroup(self) QgsVectorLayerEditBufferGroup | None[source]

Returns the edit buffer group

Added in version 3.26.

Return type:

Optional[QgsVectorLayerEditBufferGroup]

elevationProperties(self) QgsProjectElevationProperties | None[source]

Returns the project’s elevation properties, which contains the project’s elevation related settings.

Added in version 3.26.

Return type:

Optional[QgsProjectElevationProperties]

elevationShadingRenderer(self) QgsElevationShadingRenderer[source]

Returns the elevation shading renderer used for map shading

Added in version 3.30.

Return type:

QgsElevationShadingRenderer

signal elevationShadingRendererChanged[source]

Emitted when the map shading renderer changes

Added in version 3.30.

ellipsoid(self) str[source]

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

See also

setEllipsoid()

See also

crs()

See also

verticalCrs()

Return type:

str

signal ellipsoidChanged(ellipsoid: str)[source]

Emitted when the project ellipsoid is changed.

See also

setEllipsoid()

See also

ellipsoid()

Parameters:

ellipsoid (str)

entryList(self, scope: str | None, key: str | None) List[str][source]

Returns a list of child keys with values which exist within the the specified scope and key.

This method does not return keys that contain other keys. See subkeyList() to retrieve keys which contain other keys.

Note

equivalent to QgsSettings entryList()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

Return type:

List[str]

error(self) str[source]

Returns error message from previous read/write

Return type:

str

evaluateDefaultValues(self) bool[source]

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

Deprecated since version 3.40: Test whether the flags() method returns the Qgis.ProjectFlag.EvaluateDefaultValuesOnProviderSide flag instead.

Return type:

bool

fileInfo(self) QFileInfo[source]

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()

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

Return type:

QFileInfo

fileName(self) str[source]

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()

Return type:

str

signal fileNameChanged[source]

Emitted when the file name of the project changes

filePathStorage(self) Qgis.FilePathType[source]

Returns the type of paths used when storing file paths in a QGS/QGZ project file.

Added in version 3.22.

Return type:

Qgis.FilePathType

flags(self) Qgis.ProjectFlags[source]

Returns the project’s flags, which dictate the behavior of the project.

See also

setFlags()

See also

setFlag()

Added in version 3.26.

Return type:

Qgis.ProjectFlags

generateTsFile(self, locale: str | None)[source]

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

Added in version 3.4.

Parameters:

locale (Optional[str])

gpsSettings(self) QgsProjectGpsSettings | None[source]

Returns the project’s GPS settings, which contains settings and properties relating to how a QgsProject should interact with a GPS device.

Added in version 3.30.

Return type:

Optional[QgsProjectGpsSettings]

homePath(self) str[source]

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()

Return type:

str

signal homePathChanged[source]

Emitted when the home path of the project changes.

See also

homePath()

See also

presetHomePath()

static instance() QgsProject | None[source]

Returns the QgsProject singleton instance

Return type:

Optional[QgsProject]

isDirty(self) bool[source]

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

Return type:

bool

signal isDirtyChanged(dirty: bool)[source]

Emitted when the project dirty status changes.

Parameters:

dirty (bool) – True if the project is in a dirty state and has pending unsaved changes.

Added in version 3.2.

isZipped(self) bool[source]

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

Return type:

bool

labelingEngineSettings(self) QgsLabelingEngineSettings

Returns project’s global labeling engine settings

Return type:

QgsLabelingEngineSettings

signal labelingEngineSettingsChanged[source]

Emitted when global configuration of the labeling engine changes.

lastModified(self) QDateTime[source]

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

Added in version 3.2.

Return type:

QDateTime

lastSaveDateTime(self) QDateTime[source]

Returns the date and time when the project was last saved.

Added in version 3.14.

Return type:

QDateTime

lastSaveVersion(self) QgsProjectVersion[source]

Returns the QGIS version which the project was last saved using.

Added in version 3.14.

Return type:

QgsProjectVersion

layerIsEmbedded(self, id: str | None) str[source]

Returns the source project file path if the layer with matching id is embedded from other project file.

Returns an empty string if the matching layer is not embedded.

Parameters:

id (Optional[str])

Return type:

str

signal layerLoaded(i: int, n: int)[source]

Emitted when a layer from a projects was read.

Parameters:
  • i (int) – current layer

  • n (int) – number of layers

signal layerRemoved(layerId: str)[source]

Emitted after a layer was removed from the registry.

Parameters:

layerId (str) – The ID of the layer removed.

Note

Consider using layersRemoved() instead

layerStore(self) QgsMapLayerStore | None[source]

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

Return type:

Optional[QgsMapLayerStore]

layerTreeRegistryBridge(self) QgsLayerTreeRegistryBridge | None[source]

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

Return type:

Optional[QgsLayerTreeRegistryBridge]

layerTreeRoot(self) QgsLayerTree | None[source]

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

Return type:

Optional[QgsLayerTree]

signal layerWasAdded(layer: QgsMapLayer)[source]

Emitted when a layer was added to the registry.

Note

Consider using layersAdded() instead

See also

layersAdded()

Parameters:

layer (QgsMapLayer)

signal layerWillBeRemoved(layer: QgsMapLayer)[source]

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

Parameters:

layer (QgsMapLayer) – The layer to be removed.

Note

Consider using layersWillBeRemoved() instead

See also

layerRemoved()

signal layersAdded(layers: List[QgsMapLayer])[source]

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[QgsMapLayer]) – List of layers which have been added.

See also

layerWasAdded()

signal layersRemoved(layerIds: List[str])[source]

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

Parameters:

layerIds (List[str]) – A list of IDs of the layers which were removed.

signal layersWillBeRemoved(layers: List[QgsMapLayer])[source]

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

Parameters:

layers (List[QgsMapLayer]) – A list of layers which are to be removed.

See also

layersRemoved()

layoutManager(self) QgsLayoutManager | None[source]

Returns the project’s layout manager, which manages print layouts, atlases and reports within the project.

Return type:

Optional[QgsLayoutManager]

signal legendLayersAdded(layers: List[QgsMapLayer])[source]

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[QgsMapLayer]) – List of QgsMapLayer which were added to the legend.

signal loadingLayer(layerName: str)[source]

Emitted when a layer is loaded

Parameters:

layerName (str)

signal loadingLayerMessageReceived(layerName: str, messages: List[QgsReadWriteContext.ReadWriteMessage])[source]

Emitted when loading layers has produced some messages

Parameters:

Added in version 3.2.

mainAnnotationLayer(self) QgsAnnotationLayer | None[source]

Returns the main annotation layer associated with the project.

This layer is always present in projects, and will always be rendered above any other map layers during map render jobs.

It forms the default location to place new annotation items which should appear above all map layers.

Added in version 3.16.

Return type:

Optional[QgsAnnotationLayer]

mapLayer(self, layerId: str | None) QgsMapLayer | None[source]

Retrieve a pointer to a registered layer by layer ID.

Parameters:

layerId (Optional[str]) – ID of layer to retrieve

Return type:

Optional[QgsMapLayer]

Returns:

matching layer, or None if no matching layer found

See also

mapLayers()

mapLayers(self, validOnly: bool = False) Any

Returns a map of all registered layers by layer ID.

Parameters:

validOnly (bool = False) – if set only valid layers will be returned

See also

mapLayer()

See also

layers()

Return type:

Any

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

Retrieve a list of matching registered layers by layer name.

Parameters:

layerName (Optional[str]) – name of layers to match

Return type:

List[QgsMapLayer]

Returns:

list of matching layers

See also

mapLayer()

See also

mapLayers()

mapLayersByShortName(self, shortName: str | None) 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.

Return type:

List[QgsMapLayer]

Returns:

list of matching layers

See also

mapLayer()

See also

mapLayers()

Added in version 3.10.

Parameters:

shortName (Optional[str])

mapScales(self) List[float]

Returns the list of custom project map scales.

The scales list consists of a list of scale denominator values, e.g. 1000 for a 1:1000 scale.

See also

setMapScales()

Deprecated since version 3.40: Use viewSettings() instead.

Return type:

List[float]

signal mapScalesChanged[source]

Emitted when the list of custom project map scales changes.

See also

mapScales()

See also

setMapScales()

Deprecated since version 3.40: Use viewSettings() instead.

mapThemeCollection(self) QgsMapThemeCollection | None[source]

Returns pointer to the project’s map theme collection.

Note

renamed in QGIS 3.0, formerly QgsVisibilityPresetCollection

Return type:

Optional[QgsMapThemeCollection]

signal mapThemeCollectionChanged[source]

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.

metadata(self) QgsProjectMetadata

Returns a reference to the project’s metadata store.

See also

setMetadata()

Added in version 3.2.

Return type:

QgsProjectMetadata

signal metadataChanged[source]

Emitted when the project’s metadata is changed.

See also

setMetadata()

See also

metadata()

Added in version 3.2.

signal missingDatumTransforms(missingTransforms: List[str])[source]

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

Parameters:

missingTransforms (List[str])

nonIdentifiableLayers(self) List[str][source]

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

Deprecated since version 3.4: Use QgsMapLayer.setFlags() instead.

Return type:

List[str]

signal nonIdentifiableLayersChanged(nonIdentifiableLayers: List[str])[source]

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

Deprecated since version 3.4.

Parameters:

nonIdentifiableLayers (List[str])

signal oldProjectVersionWarning[source]

Emitted when an old project file is read.

Deprecated since version 3.40: Use readVersionMismatchOccurred() instead.

originalPath(self) str[source]

Returns the original path associated with the project.

This is intended for use with non-qgs/qgz project files (see QgsCustomProjectOpenHandler) in order to allow custom project open handlers to specify the original file name of the project. For custom project formats, it is NOT appropriate to call setFileName() with the original project path, as this causes the original (non QGIS) project file to be overwritten when the project is next saved.

Added in version 3.14.

Return type:

str

pathResolver(self) QgsPathResolver[source]

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

Return type:

QgsPathResolver

presetHomePath(self) str[source]

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()

Added in version 3.2.

Return type:

str

signal projectColorsChanged[source]

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

Added in version 3.6.

signal projectSaved[source]

Emitted when the project file has been written and closed.

projectStorage(self) QgsProjectStorage | None[source]

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.

Added in version 3.2.

Return type:

Optional[QgsProjectStorage]

read(self, filename: str | None, flags: Qgis.ProjectReadFlags | Qgis.ProjectReadFlag = Qgis.ProjectReadFlags()) bool[source]

Reads given project file from the given file.

Parameters:
  • filename (Optional[str]) – name of project file to read

  • flags (Union[Qgis.ProjectReadFlags, Qgis.ProjectReadFlag] = Qgis.ProjectReadFlags()) – optional flags which control the read behavior of projects

Return type:

bool

Returns:

True if project file has been read successfully

read(self, flags: Qgis.ProjectReadFlags | Qgis.ProjectReadFlag = Qgis.ProjectReadFlags()) bool[source]

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.

Return type:

bool

Returns:

True if project file has been read successfully

Parameters:

flags (Union[Qgis.ProjectReadFlags, Qgis.ProjectReadFlag] = Qgis.ProjectReadFlags())

readBoolEntry(self, scope: str | None, key: str | None, def_: bool = False)[source]

Reads a boolean from the specified scope and key.

Parameters:
  • scope (Optional[str]) – entry scope (group) name

  • key (Optional[str]) – entry key name. Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values.

  • def (bool = False) -> (bool) – default value to return if the specified key does not exist within the scope.

  • def

Returns:

  • entry value as boolean from scope given its key

  • ok: set to True if key exists and has been successfully retrieved as a boolean

readDoubleEntry(self, scope: str | None, key: str | None, def_: float = 0)[source]

Reads a double from the specified scope and key.

Parameters:
  • scope (Optional[str]) – entry scope (group) name

  • key (Optional[str]) – entry key name. Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values.

  • def (float = 0) -> (float) – default value to return if the specified key does not exist within the scope.

  • def

Returns:

  • entry value as double from scope given its key

  • ok: set to True if key exists and has been successfully retrieved as a double

readEntry(self, scope: str | None, key: str | None, def_: str | None = '')[source]

Reads a string from the specified scope and key.

Parameters:
  • scope (Optional[str]) – entry scope (group) name

  • key (Optional[str]) – entry key name. Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values.

  • def (Optional[str] = '') -> (str) – default value to return if the specified key does not exist within the scope.

  • def

Returns:

  • entry value as string from scope given its key

  • ok: set to True if key exists and has been successfully retrieved as a string value

readLayer(self, layerNode: QDomNode) bool[source]

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 (QDomNode) – represents a QgsProject DOM node that encodes a specific layer.

Return type:

bool

readListEntry(self, scope: str | None, key: str | None, def_: Iterable[str | None] = [])[source]

Reads a string list from the specified scope and key.

Parameters:
  • scope (Optional[str]) – entry scope (group) name

  • key (Optional[str]) – entry key name. Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values.

  • def (Iterable[Optional[str]] = []) -> (List[str]) – default value to return if the specified key does not exist within the scope.

  • def

Returns:

  • entry value as a string list

  • ok: set to True if key exists and has been successfully retrieved as a string list

signal readMapLayer(mapLayer: QgsMapLayer, layerNode: QDomElement)[source]

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 (QgsMapLayer) – The map layer which is being initialized

  • layerNode (QDomElement) – The layer node from the project file

readNumEntry(self, scope: str | None, key: str | None, def_: int = 0)[source]

Reads an integer from the specified scope and key.

Parameters:
  • scope (Optional[str]) – entry scope (group) name

  • key (Optional[str]) – entry key name. Keys are ‘/’-delimited entries, implying a hierarchy of keys and corresponding values.

  • def (int = 0) -> (int) – default value to return if the specified key does not exist within the scope.

  • def

Returns:

  • entry value as integer from scope given its key

  • ok: set to True if key exists and has been successfully retrieved as an integer

readPath(self, filename: str | None) str[source]

Transforms a filename read from the project file to an absolute path.

Parameters:

filename (Optional[str])

Return type:

str

signal readProject(document: QDomDocument)[source]

Emitted when a project is being read.

Parameters:

document (QDomDocument)

signal readProjectWithContext(document: QDomDocument, context: QgsReadWriteContext)[source]

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

Parameters:
signal readVersionMismatchOccurred(fileVersion: str)[source]

Emitted when a project is read and the version of QGIS used to save the project differs from the current QGIS version.

The fileVersion argument indicates the version of QGIS used to save the project.

Note

Not available in Python bindings

Added in version 3.26.

Parameters:

fileVersion (str)

registerTranslatableContainers(self, translationContext: QgsTranslationContext | None, parent: QgsAttributeEditorContainer | None, layerId: str | None)[source]

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

Parameters:
  • translationContext (Optional[QgsTranslationContext]) – where the objects will be registered

  • parent (Optional[QgsAttributeEditorContainer]) – parent-container containing list of children

  • layerId (Optional[str]) – to store under the correct context

Added in version 3.4.

registerTranslatableObjects(self, translationContext: QgsTranslationContext | None)[source]

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

Added in version 3.4.

Parameters:

translationContext (Optional[QgsTranslationContext])

relationManager(self) QgsRelationManager | None[source]
Return type:

Optional[QgsRelationManager]

reloadAllLayers(self)[source]

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

signal removeAll[source]

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.

removeAllMapLayers(self)[source]

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()

removeAttachedFile(self, path: str | None) bool[source]

Removes the attached file

Parameters:

path (Optional[str]) – Path to the attached file

Return type:

bool

Returns:

Whether removal succeeded.

Added in version 3.22.

removeEntry(self, scope: str | None, key: str | None) bool[source]

Remove the given key from the specified scope.

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

Return type:

bool

removeMapLayer(self, layerId: str | None)[source]

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 (Optional[str]) – ID of the layer to remove

Note

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

removeMapLayer(self, layer: QgsMapLayer | None)[source]

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 (Optional[QgsMapLayer]) – The layer to remove. None values are ignored.

Note

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

removeMapLayers(self, layers: List[QgsVectorLayer] | List[str])[source]

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 (Union[List[QgsVectorLayer], List[str]]) – list of layers or list of layer IDs of the layers to remove

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 3.4: Use QgsMapLayer.flags() instead.

Added in version 3.2.

Return type:

Set[QgsMapLayer]

resolveAttachmentIdentifier(self, identifier: str | None) str[source]

Resolves an attachment identifier to a attachment file path

Parameters:

identifier (Optional[str]) – An attachment identifier

Return type:

str

Returns:

The attachment file path, or an empty string if the identifier is invalid

Added in version 3.22.

rollBack(self, stopEditing: bool = True, vectorLayer: QgsVectorLayer | None = None)[source]

Stops a current editing operation on vectorLayer and discards any uncommitted edits.

Parameters:
  • stopEditing (bool = True) – if set to False, the layer will stay in editing mode. Otherwise the layer editing mode will be disabled if the rollback is successful.

  • vectorLayer (Optional[QgsVectorLayer] = None) -> (bool) – for which the changes will be rolled back. For buffered transactions this parameter is not mandatory, as the changes from all layers will be rolled back.

Returns:

  • True if the rollback was successful.

  • rollbackErrors: a list of descriptive errors if the rollback fails.

See also

startEditing()

See also

commitChanges()

Added in version 3.26.

saveUser(self) str[source]

Returns the user name that did the last save.

Added in version 3.12.

Return type:

str

saveUserFullName(self) str[source]

Returns the full user name that did the last save.

See also

saveUser()

Added in version 3.12.

Return type:

str

scaleMethod(self) Qgis.ScaleCalculationMethod[source]

Returns the method to use for map scale calculations for the project.

See also

setScaleMethod()

Added in version 3.44.

Return type:

Qgis.ScaleCalculationMethod

signal scaleMethodChanged[source]

Emitted when the project’s scale method is changed.

See also

scaleMethod()

See also

setScaleMethod()

Added in version 3.44.

selectionColor(self) QColor[source]

Returns the color used to highlight selected features

Added in version 3.10.

Return type:

QColor

signal selectionColorChanged[source]

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

Added in version 3.10.

sensorManager(self) QgsSensorManager | None[source]

Returns the project’s sensor manager, which manages sensors within the project.

Added in version 3.32.

Return type:

Optional[QgsSensorManager]

setAreaUnits(self, unit: Qgis.AreaUnit)[source]

Sets the default area measurement units for the project.

See also

areaUnits()

Parameters:

unit (Qgis.AreaUnit)

setAutoTransaction(self, autoTransaction: bool)[source]

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.

Warning

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

Deprecated since version 3.26: Use setTransactionMode() instead.

Parameters:

autoTransaction (bool)

setAvoidIntersectionsLayers(self, layers: Iterable[QgsVectorLayer])[source]

Sets the list of layers with which intersections should be avoided. Only used if the avoid intersection mode is set to advanced. Line and point layers will not be added.

Parameters:

layers (Iterable[QgsVectorLayer])

setAvoidIntersectionsMode(self, mode: Qgis.AvoidIntersectionsMode)[source]

Sets the avoid intersections mode.

Added in version 3.14.

Parameters:

mode (Qgis.AvoidIntersectionsMode)

setBackgroundColor(self, color: QColor | Qt.GlobalColor)[source]

Sets the default background color used by default map canvases.

Added in version 3.10.

Parameters:

color (Union[QColor, Qt.GlobalColor])

setBadLayerHandler(self, handler: QgsProjectBadLayerHandler | None)[source]

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

Parameters:

handler (Optional[QgsProjectBadLayerHandler])

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

Sets the project’s native coordinate reference system.

If adjustEllipsoid is set to True, the ellipsoid of this project will be set to the ellipsoid imposed by the CRS.

Changing the CRS will trigger a crsChanged() signal. Additionally, if crs is a compound CRS, then the verticalCrsChanged() signal will also be emitted.

See also

crs()

See also

crsChanged()

See also

setVerticalCrs()

See also

setEllipsoid()

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

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

Parameters:

customVariables (Dict[str, Any])

setDataDefinedServerProperties(self, properties: QgsPropertyCollection)[source]

Sets the data defined properties used for overrides in user defined server parameters to properties

Added in version 3.14.

Parameters:

properties (QgsPropertyCollection)

setDirty(self, b: bool = True)[source]

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

Parameters:

b (bool = True)

setDistanceUnits(self, unit: Qgis.DistanceUnit)[source]

Sets the default distance measurement units for the project.

See also

distanceUnits()

See also

setAreaUnits()

Parameters:

unit (Qgis.DistanceUnit)

setElevationShadingRenderer(self, elevationShadingRenderer: QgsElevationShadingRenderer)[source]

Sets the elevation shading renderer used for global map shading

Added in version 3.30.

Parameters:

elevationShadingRenderer (QgsElevationShadingRenderer)

setEllipsoid(self, ellipsoid: str | None)[source]

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

See also

ellipsoid()

See also

setCrs()

See also

setVerticalCrs()

Parameters:

ellipsoid (Optional[str])

setEvaluateDefaultValues(self, evaluateDefaultValues: bool)[source]

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

Deprecated since version 3.40: Use setFlag( Qgis.ProjectFlag.EvaluateDefaultValuesOnProviderSide ) instead.

Parameters:

evaluateDefaultValues (bool)

setFileName(self, name: str | None)[source]

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 (Optional[str]) – project file name

See also

fileName()

setFilePathStorage(self, type: Qgis.FilePathType)[source]

Sets the type of paths used when storing file paths in a QGS/QGZ project file.

Added in version 3.22.

Parameters:

type (Qgis.FilePathType)

setFlag(self, flag: Qgis.ProjectFlag, enabled: bool = True)[source]

Sets whether a project flag is enabled.

See also

flags()

See also

setFlags()

Added in version 3.26.

Parameters:
setFlags(self, flags: Qgis.ProjectFlags | Qgis.ProjectFlag)[source]

Sets the project’s flags, which dictate the behavior of the project.

See also

flags()

See also

setFlag()

Added in version 3.26.

Parameters:

flags (Union[Qgis.ProjectFlags, Qgis.ProjectFlag])

static setInstance(project: QgsProject | None)[source]

Set the current project singleton instance to project

Note

this method is provided mainly for the server, which caches the projects and (potentially) needs to switch the current instance on every request.

Warning

calling this method can have serious, unintended consequences, including instability, data loss and undefined behavior. Use with EXTREME caution!

See also

instance()

Added in version 3.10.11.

Parameters:

project (Optional[QgsProject])

setLabelingEngineSettings(self, settings: QgsLabelingEngineSettings)[source]

Sets project’s global labeling engine settings

Parameters:

settings (QgsLabelingEngineSettings)

setMapScales(self, scales: Iterable[float])[source]

Sets the list of custom project map scales.

The scales list consists of a list of scale denominator values, e.g. 1000 for a 1:1000 scale.

See also

mapScales()

Deprecated since version 3.40: Use viewSettings() instead.

Parameters:

scales (Iterable[float])

setMetadata(self, metadata: QgsProjectMetadata)[source]

Sets the project’s metadata store.

See also

metadata()

Added in version 3.2.

Parameters:

metadata (QgsProjectMetadata)

setNonIdentifiableLayers(self, layers: Iterable[QgsMapLayer])[source]

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

Deprecated since version 3.4: Use QgsMapLayer.setFlags() instead.

Parameters:

layers (Iterable[QgsMapLayer])

setNonIdentifiableLayers(self, layerIds: Iterable[str | None])[source]

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

Deprecated since version 3.4: Use QgsMapLayer.setFlags() instead.

Parameters:

layerIds (Iterable[Optional[str]])

setOriginalPath(self, path: str | None)[source]

Sets the original path associated with the project.

This is intended for use with non-qgs/qgz project files (see QgsCustomProjectOpenHandler) in order to allow custom project open handlers to specify the original file name of the project. For custom project formats, it is NOT appropriate to call setFileName() with the original project path, as this causes the original (non QGIS) project file to be overwritten when the project is next saved.

See also

originalPath()

Added in version 3.14.

Parameters:

path (Optional[str])

setPresetHomePath(self, path: str | None)[source]

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()

Added in version 3.2.

Parameters:

path (Optional[str])

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

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

Added in version 3.6.

Parameters:

colors (Iterable[Tuple[Union[QColor, Qt.GlobalColor], Optional[str]]])

setRequiredLayers(self, layers: Iterable[QgsMapLayer])[source]

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 3.4: Use QgsMapLayer.setFlags() instead.

Added in version 3.2.

Parameters:

layers (Iterable[QgsMapLayer])

setScaleMethod(self, method: Qgis.ScaleCalculationMethod)[source]

Sets the method to use for map scale calculations for the project.

See also

scaleMethod()

Added in version 3.44.

Parameters:

method (Qgis.ScaleCalculationMethod)

setSelectionColor(self, color: QColor | Qt.GlobalColor)[source]

Sets the color used to highlight selected features.

See also

selectionColor()

Added in version 3.10.

Parameters:

color (Union[QColor, Qt.GlobalColor])

setSnappingConfig(self, snappingConfig: QgsSnappingConfig)[source]

The snapping configuration for this project.

Parameters:

snappingConfig (QgsSnappingConfig)

setTitle(self, title: str | None)[source]

Sets the project’s title.

Parameters:

title (Optional[str]) – new title

Note

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

See also

title()

setTopologicalEditing(self, enabled: bool)[source]

Convenience function to set topological editing

Parameters:

enabled (bool)

setTransactionMode(self, transactionMode: Qgis.TransactionMode) bool[source]

Set transaction mode

Return type:

bool

Returns:

True if the transaction mode could be changed

Note

Transaction mode can be changed only when all layers are not in edit mode.

See also

Qgis.TransactionMode

Added in version 3.26.

Parameters:

transactionMode (Qgis.TransactionMode)

setTransformContext(self, context: QgsCoordinateTransformContext)[source]

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.

Parameters:

context (QgsCoordinateTransformContext)

setTrustLayerMetadata(self, trust: bool)[source]

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:

trust (bool) – True to trust the project, False otherwise

Deprecated since version 3.40: Use setFlag( Qgis.ProjectFlag.TrustStoredLayerStatistics ) instead.

setUseProjectScales(self, enabled: bool)[source]

Sets whether project mapScales() are enabled.

See also

setMapScales()

Deprecated since version 3.40: Use viewSettings() instead.

Parameters:

enabled (bool)

setVerticalCrs(self, crs: QgsCoordinateReferenceSystem)[source]

Sets the project’s vertical coordinate reference system.

The verticalCrsChanged() signal will be raised if the vertical CRS is changed.

Note

If the project crs() is a compound CRS, then the CRS returned for verticalCrs() will be the vertical component of crs(). Otherwise it will be the value explicitly set by this call.

Parameters:

crs (QgsCoordinateReferenceSystem) -> (bool) – the vertical CRS

Returns:

  • True if vertical CRS was successfully set

  • errorMessage: a descriptive message if the vertical CRS could not be set

See also

verticalCrs()

See also

setCrs()

Added in version 3.38.

snappingConfig(self) QgsSnappingConfig[source]

The snapping configuration for this project.

Return type:

QgsSnappingConfig

signal snappingConfigChanged(config: QgsSnappingConfig)[source]

Emitted whenever the configuration for snapping has changed.

Parameters:

config (QgsSnappingConfig)

startEditing(self, vectorLayer: QgsVectorLayer | None = None) bool[source]

Makes the layer editable.

This starts an edit session on vectorLayer. Changes made in this edit session will not be made persistent until commitChanges() is called, and can be reverted by calling rollBack().

Return type:

bool

Returns:

True if the layer was successfully made editable, or False if the operation failed (e.g. due to an underlying read-only data source, or lack of edit support by the backend data provider).

See also

commitChanges()

See also

rollBack()

Added in version 3.26.

Parameters:

vectorLayer (Optional[QgsVectorLayer] = None)

styleSettings(self) QgsProjectStyleSettings | None[source]

Returns the project’s style settings, which contains settings and properties relating to how a QgsProject should handle styling. (e.g. styling of a newly added vector layer)

Added in version 3.26.

Return type:

Optional[QgsProjectStyleSettings]

subkeyList(self, scope: str | None, key: str | None) List[str][source]

Returns a list of child keys which contain other keys that exist within the the specified scope and key.

This method only returns keys with keys, it will not return keys that contain only values. See entryList() to retrieve keys with values.

Note

equivalent to QgsSettings subkeyList()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

Return type:

List[str]

takeMapLayer(self, layer: QgsMapLayer | None) QgsMapLayer | None[source]

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()

Parameters:

layer (Optional[QgsMapLayer])

Return type:

Optional[QgsMapLayer]

timeSettings(self) QgsProjectTimeSettings | None[source]

Returns the project’s time settings, which contains the project’s temporal range and other time based settings.

Added in version 3.14.

Return type:

Optional[QgsProjectTimeSettings]

title(self) str[source]

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().

Return type:

str

topologicalEditing(self) bool[source]

Convenience function to query topological editing status

Return type:

bool

signal topologicalEditingChanged[source]

Emitted when the topological editing flag has changed.

transactionGroup(self, providerKey: str | None, connString: str | None) QgsTransactionGroup | None[source]

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

Returns None if a matching transaction group is not available.

Added in version 3.2.

Parameters:
  • providerKey (Optional[str])

  • connString (Optional[str])

Return type:

Optional[QgsTransactionGroup]

signal transactionGroupsChanged[source]

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

transactionMode(self) Qgis.TransactionMode[source]

Returns the transaction mode

See also

Qgis.TransactionMode

Added in version 3.26.

Return type:

Qgis.TransactionMode

signal transactionModeChanged[source]

Emitted when the transaction mode has changed.

Added in version 3.38.

transformContext(self) QgsCoordinateTransformContext[source]

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.

Return type:

QgsCoordinateTransformContext

signal transformContextChanged[source]

Emitted when the project transformContext() is changed.

trustLayerMetadata(self) bool[source]

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.

Deprecated since version 3.40: Test whether the flags() method returns the Qgis.ProjectFlag.TrustStoredLayerStatistics flag instead.

Return type:

bool

useProjectScales(self) bool[source]

Returns True if project mapScales() are enabled.

See also

mapScales()

Deprecated since version 3.40: Use viewSettings() instead.

Return type:

bool

validCount(self) int[source]

Returns the number of registered valid layers.

Return type:

int

verticalCrs(self) QgsCoordinateReferenceSystem[source]

Returns the project’s vertical coordinate reference system.

If the project crs() is a compound CRS, then the CRS returned will be the vertical component of crs(). Otherwise it will be the value explicitly set by a call to setVerticalCrs().

The returned CRS will be invalid if the project has no vertical CRS.

Note

Consider also using crs3D(), which will return a CRS which takes into account both crs() and verticalCrs().

See also

crs()

See also

crs3D()

See also

setVerticalCrs()

Added in version 3.38.

Return type:

QgsCoordinateReferenceSystem

signal verticalCrsChanged[source]

Emitted when the verticalCrs() of the project has changed.

This signal will be emitted whenever the vertical CRS of the project is changed, either as a direct result of a call to setVerticalCrs() or when setCrs() is called with a compound CRS.

See also

crsChanged()

See also

crs3DChanged()

See also

setCrs()

See also

setVerticalCrs()

See also

verticalCrs()

Added in version 3.38.

viewSettings(self) QgsProjectViewSettings | None[source]

Returns the project’s view settings, which contains settings and properties relating to how a QgsProject should be viewed and behave inside a map canvas (e.g. map scales and default view extent)

Added in version 3.10.1.

Return type:

Optional[QgsProjectViewSettings]

viewsManager(self) QgsMapViewsManager | None[source]

Returns the project’s views manager, which manages map views (including 3d maps) in the project.

Added in version 3.24.

Return type:

Optional[QgsMapViewsManager]

write(self, filename: str | None) bool[source]

Writes the project to a file.

Parameters:

filename (Optional[str]) – destination file

Return type:

bool

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

write(self) bool[source]

Writes the project to its current associated file (see fileName() ).

Return type:

bool

Returns:

True if project was written successfully

Note

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

writeEntry(self, scope: str | None, key: str | None, value: int) bool[source]

Write an integer value 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.

See also

readNumEntry()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

  • value (int)

Return type:

bool

writeEntry(self, scope: str | None, key: str | None, value: str | None) bool[source]

Write a string value 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.

See also

readEntry()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

  • value (Optional[str])

Return type:

bool

writeEntry(self, scope: str | None, key: str | None, value: Iterable[str | None]) bool[source]

Write a string list value 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.

See also

readListEntry()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

  • value (Iterable[Optional[str]])

Return type:

bool

writeEntryBool(self, scope: str | None, key: str | None, value: bool) bool

Write a boolean value 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.

See also

readBoolEntry()

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

  • value (bool)

Return type:

bool

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

Write a double value 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.

Parameters:
  • scope (Optional[str])

  • key (Optional[str])

  • value (float)

Return type:

bool

signal writeMapLayer(mapLayer: QgsMapLayer, layerElem: QDomElement, doc: QDomDocument)[source]

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

Parameters:
  • mapLayer (QgsMapLayer) – The map layer which is being initialized

  • layerElem (QDomElement) – The layer element from the project file

  • doc (QDomDocument) – The document

writePath(self, filename: str | None) str[source]

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.

Parameters:

filename (Optional[str])

Return type:

str

signal writeProject(document: QDomDocument)[source]

Emitted when the project is being written.

Parameters:

document (QDomDocument)