Subgroup: Vector

Class: QgsVectorLayer

class qgis.core.QgsVectorLayer(path: str = '', baseName: str = '', providerLib: str = '', options: QgsVectorLayer.LayerOptions = QgsVectorLayer.LayerOptions())

Bases: qgis._core.QgsMapLayer, qgis._core.QgsExpressionContextGenerator, qgis._core.QgsExpressionContextScopeGenerator, qgis._core.QgsFeatureSink, qgis._core.QgsFeatureSource

Constructor - creates a vector layer

The QgsVectorLayer is constructed by instantiating a data provider. The provider interprets the supplied path (url) of the data source to connect to and access the data.

Parameters:
  • path – The path or url of the parameter. Typically this encodes parameters used by the data provider as url query items.
  • baseName – The name used to represent the layer in the legend
  • providerLib – The name of the data provider, e.g., “memory”, “postgres”
  • options – layer load options

Represents a vector layer which manages a vector based data sets.

The QgsVectorLayer is instantiated by specifying the name of a data provider, such as postgres or wfs, and url defining the specific data set to connect to. The vector layer constructor in turn instantiates a QgsVectorDataProvider subclass corresponding to the provider type, and passes it the url. The data provider connects to the data source.

The QgsVectorLayer provides a common interface to the different data types. It also manages editing transactions.

Sample usage of the QgsVectorLayer class:

The main data providers supported by QGIS are listed below.

section providers Vector data providers

subsection memory Memory data providerType (memory)

The memory data provider is used to construct in memory data, for example scratch data or data generated from spatial operations such as contouring. There is no inherent persistent storage of the data. The data source uri is constructed. The url specifies the geometry type (“point”, “linestring”, “polygon”, “multipoint”,”multilinestring”,”multipolygon”), optionally followed by url parameters as follows:

  • crs=definition

Defines the coordinate reference system to use for the layer. definition is any string accepted by QgsCoordinateReferenceSystem.createFromString()

  • index=yes

Specifies that the layer will be constructed with a spatial index

  • field=name:type(length,precision)

Defines an attribute of the layer. Multiple field parameters can be added to the data provider definition. type is one of “integer”, “double”, “string”.

An example url is “Point?crs=epsg:4326&field=id:integer&field=name:string(20)&index=yes”

subsection ogr OGR data provider (ogr)

Accesses data using the OGR drivers (http://www.gdal.org/ogr/ogr_formats.html). The url is the OGR connection string. A wide variety of data formats can be accessed using this driver, including file based formats used by many GIS systems, database formats, and web services. Some of these formats are also supported by custom data providers listed below.

subsection spatialite SpatiaLite data provider (spatialite)

Access data in a SpatiaLite database. The url defines the connection parameters, table, geometry column, and other attributes. The url can be constructed using the QgsDataSourceUri class.

subsection postgres PostgreSQL data provider (postgres)

Connects to a PostgreSQL database. The url defines the connection parameters, table, geometry column, and other attributes. The url can be constructed using the QgsDataSourceUri class.

subsection mssql Microsoft SQL server data provider (mssql)

Connects to a Microsoft SQL server database. The url defines the connection parameters, table, geometry column, and other attributes. The url can be constructed using the QgsDataSourceUri class.

subsection wfs WFS (web feature service) data provider (wfs)

Used to access data provided by a web feature service.

The url can be a HTTP url to a WFS server (legacy, e.g. http://foobar/wfs?TYPENAME=xxx&SRSNAME=yyy[&FILTER=zzz]), or, starting with QGIS 2.16, a URI constructed using the QgsDataSourceUri class with the following parameters : - url=string (mandatory): HTTP url to a WFS server endpoint. e.g http://foobar/wfs - typename=string (mandatory): WFS typename - srsname=string (recommended): SRS like ‘EPSG:XXXX’ - username=string - password=string - authcfg=string - version=auto/1.0.0/1.1.0/2.0.0 -sql=string: full SELECT SQL statement with optional WHERE, ORDER BY and possibly with JOIN if supported on server - filter=string: QGIS expression or OGC/FES filter - restrictToRequestBBOX=1: to download only features in the view extent (or more generally in the bounding box of the feature iterator) - maxNumFeatures=number - IgnoreAxisOrientation=1: to ignore EPSG axis order for WFS 1.1 or 2.0 - InvertAxisOrientation=1: to invert axis order - hideDownloadProgressDialog=1: to hide the download progress dialog

The ‘FILTER’ query string parameter can be used to filter the WFS feature type. The ‘FILTER’ key value can either be a QGIS expression or an OGC XML filter. If the value is set to a QGIS expression the driver will turn it into OGC XML filter before passing it to the WFS server. Beware the QGIS expression filter only supports” =, !=, <, >, <=, >=, AND, OR, NOT, LIKE, IS NULL” attribute operators, “BBOX, Disjoint, Intersects, Touches, Crosses, Contains, Overlaps, Within” spatial binary operators and the QGIS local “geomFromWKT, geomFromGML” geometry constructor functions.

Also note:

  • You can use various functions available in the QGIS Expression list,

however the function must exist server side and have the same name and arguments to work.

  • Use the special $geometry parameter to provide the layer geometry column as input

into the spatial binary operators e.g intersects($geometry, geomFromWKT(‘POINT (5 6)’))

subsection delimitedtext Delimited text file data provider (delimitedtext)

Accesses data in a delimited text file, for example CSV files generated by spreadsheets. The contents of the file are split into columns based on specified delimiter characters. Each record may be represented spatially either by an X and Y coordinate column, or by a WKT (well known text) formatted columns.

The url defines the filename, the formatting options (how the text in the file is divided into data fields, and which fields contain the X,Y coordinates or WKT text definition. The options are specified as url query items.

At its simplest the url can just be the filename, in which case it will be loaded as a CSV formatted file.

The url may include the following items:

  • encoding=UTF-8

Defines the character encoding in the file. The default is UTF-8. To use the default encoding for the operating system use “System”.

  • type=(csv|regexp|whitespace|plain)

Defines the algorithm used to split records into columns. Records are defined by new lines, except for csv format files for which quoted fields may span multiple records. The default type is csv.

  • “csv” splits the file based on three sets of characters:

delimiter characters, quote characters, and escape characters. Delimiter characters mark the end of a field. Quote characters enclose a field which can contain delimiter characters, and newlines. Escape characters cause the following character to be treated literally (including delimiter, quote, and newline characters). Escape and quote characters must be different from delimiter characters. Escape characters that are also quote characters are treated specially - they can only escape themselves within quotes. Elsewhere they are treated as quote characters. The defaults for delimiter, quote, and escape are ‘,’, ‘”’, ‘”’. - “regexp” splits each record using a regular expression (see QRegExp documentation for details). - “whitespace” splits each record based on whitespace (on or more whitespace characters. Leading whitespace in the record is ignored. - “plain” is provided for backwards compatibility. It is equivalent to CSV except that the default quote characters are single and double quotes, and there is no escape characters.

  • delimiter=characters

Defines the delimiter characters used for csv and plain type files, or the regular expression for regexp type files. It is a literal string of characters except that “t” may be used to represent a tab character.

  • quote=characters

Defines the characters that are used as quote characters for csv and plain type files.

  • escape=characters

Defines the characters used to escape delimiter, quote, and newline characters.

  • skipLines=n

Defines the number of lines to ignore at the beginning of the file (default 0)

  • useHeader=(yes|no)

Defines whether the first record in the file (after skipped lines) contains column names (default yes)

  • trimFields=(yes|no)

If yes then leading and trailing whitespace will be removed from fields

  • skipEmptyFields=(yes|no)

If yes then empty fields will be discarded (equivalent to concatenating consecutive delimiters)

  • maxFields=#

Specifies the maximum number of fields to load for each record. Additional fields will be discarded. Default is 0 - load all fields.

  • decimalPoint=c

Defines a character that is used as a decimal point in the numeric columns The default is ‘.’.

  • xField=column yField=column

Defines the name of the columns holding the x and y coordinates for XY point geometries. If the useHeader is no (ie there are no column names), then this is the column number (with the first column as 1).

  • xyDms=(yes|no)

If yes then the X and Y coordinates are interpreted as degrees/minutes/seconds format (fairly permissively), or degree/minutes format.

  • wktField=column

Defines the name of the columns holding the WKT geometry definition for WKT geometries. If the useHeader is no (ie there are no column names), then this is the column number (with the first column as 1).

  • geomType=(point|line|polygon|none)

Defines the geometry type for WKT type geometries. QGIS will only display one type of geometry for the layer - any others will be ignored when the file is loaded. By default the provider uses the type of the first geometry in the file. Use geomType to override this type.

geomType can also be set to none, in which case the layer is loaded without geometries.

  • subset=expression

Defines an expression that will identify a subset of records to display

  • crs=crsstring

Defines the coordinate reference system used for the layer. This can be any string accepted by QgsCoordinateReferenceSystem.createFromString()

-subsetIndex=(yes|no)

Determines whether the provider generates an index to improve the efficiency of subsets. The default is yes

-spatialIndex=(yes|no)

Determines whether the provider generates a spatial index. The default is no.

-watchFile=(yes|no)

Defines whether the file will be monitored for changes. The default is to monitor for changes.

  • quiet

Errors encountered loading the file will not be reported in a user dialog if quiet is included (They will still be shown in the output log).

subsection gpx GPX data provider (gpx)

Provider reads tracks, routes, and waypoints from a GPX file. The url defines the name of the file, and the type of data to retrieve from it (“track”, “route”, or “waypoint”).

An example url is “/home/user/data/holiday.gpx?type=route”

subsection grass Grass data provider (grass)

Provider to display vector data in a GRASS GIS layer.

TODO QGIS3: Remove virtual from non-inherited methods (like isModified)

See also

QgsVectorLayerUtils

Methods

actions Returns all layer actions defined on this layer.
addAttribute Add an attribute field (but does not commit it) returns true if the field was added
addCurvedPart
addCurvedRing Adds a ring to polygon/multipolygon features (takes ownership)
addExpressionField Add a new field which is calculated by the expression specified
addFeature
addFeatures
addJoin Joins another vector layer to this layer
addPart Adds a new part polygon to a multipart feature
addPartV2 Adds a new part polygon to a multipart feature
addRing Adds a ring to polygon/multipolygon features
addTopologicalPoints Adds topological points for every vertex of the geometry.
aggregate Calculates an aggregated value from the layer’s features.
appendError
attributeAlias Returns the alias of an attribute name or a null string if there is no alias.
attributeAliases Returns a map of field name to attribute alias
attributeDisplayName Convenience function that returns the attribute alias if defined or the field name else
attributeList Returns list of attribute indexes.
attributeTableConfig Returns the attribute table configuration object.
auxiliaryLayer Returns the current auxiliary layer.
beginEditCommand Create edit command for undo/redo operations
boundingBoxOfSelected Returns the bounding box of the selected features.
capabilitiesString Capabilities for this layer, comma separated and translated.
changeAttributeValue Changes an attribute value for a feature (but does not immediately commit the changes).
changeAttributeValues Changes attributes’ values for a feature (but does not immediately commit the changes).
changeGeometry Changes a feature’s geometry within the layer’s edit buffer (but does not immediately commit the changes).
childEvent
clone Returns a new instance equivalent to this one.
commitChanges Attempts to commit to the underlying data provider any buffered changes made since the last to call to startEditing().
commitErrors Returns a list containing any error messages generated when attempting to commit changes to the layer.
conditionalStyles Returns the conditional styles that are set for this layer.
connectNotify
constraintDescription Returns the descriptive name for the constraint expression for a specified field index.
constraintExpression Returns the constraint expression for for a specified field index, if set.
countSymbolFeatures Count features for symbols.
createExpressionContext
createExpressionContextScope
createMapRenderer Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context
customEvent
dataComment Returns a description for this layer as defined in the data provider.
dataProvider
decodedSource
defaultValue Returns the calculated default value for the specified field index.
defaultValueDefinition Returns the definition of the expression used when calculating the default value for a field.
deleteAttribute Deletes an attribute field (but does not commit it).
deleteAttributes Deletes a list of attribute fields (but does not commit it)
deleteFeature Deletes a feature from the layer (but does not commit it).
deleteFeatures Deletes a set of features from the layer (but does not commit it)
deleteSelectedFeatures Deletes the selected features
deleteStyleFromDatabase Delete a style from the database
deleteVertex Deletes a vertex from a feature.
dependencies Gets the list of dependencies.
deselect Deselect feature by its ID
destroyEditCommand Destroy active command and reverts all changes in it
diagramLayerSettings
diagramRenderer
diagramsEnabled Returns whether the layer contains diagrams which are enabled and should be drawn.
disconnectNotify
displayExpression Returns the preview expression, used to create a human readable preview string.
displayField This is a shorthand for accessing the displayExpression if it is a simple field.
drawVertexMarker Draws a vertex symbol at (screen) coordinates x, y.
editBuffer Buffer with uncommitted editing operations.
editFormConfig Returns the configuration of the form used to represent this vector layer.
editorWidgetSetup The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field at index.
encodedSource
endEditCommand Finish edit command and add it to undo/redo stack
excludeAttributesWfs A set of attributes that are not advertised in WFS requests with QGIS server.
excludeAttributesWms A set of attributes that are not advertised in WMS requests with QGIS server.
expressionField Returns the expression used for a given expression field
extent
featureBlendMode Returns the current blending mode for features
featureCount Number of features rendered with specified legend key.
fieldConstraints Returns any constraints which are present for a specified field index.
fieldConstraintsAndStrength Returns a map of constraint with their strength for a specific field of the layer.
fields Returns the list of fields of this layer.
geometryType Returns point, line or polygon
getFeature Query the layer for the feature with the given id.
getFeatures Query the layer for features specified in request.
getSelectedFeatures Returns an iterator of the selected features.
getStyleFromDatabase Will return the named style corresponding to style id provided
hasDependencyCycle
htmlMetadata
insertVertex Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature Not meaningful for Point geometries
invertSelection Select not selected features and deselect selected ones
invertSelectionInRectangle Invert selection of features found within the search rectangle (in layer’s coordinates)
isAuxiliaryField Returns true if the field comes from the auxiliary layer, false otherwise.
isEditCommandActive Test if an edit command is active
isEditable Returns true if the provider is in editing mode
isModified Returns true if the provider has been modified since the last commit
isSignalConnected
isSpatial Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeometry
joinBuffer Returns the join buffer object.
labeling Access to labeling configuration.
labelsEnabled Returns whether the layer contains labels which are enabled and should be drawn.
listStylesInDatabase Lists all the style in db split into related to the layer and not related to
loadAuxiliaryLayer Loads the auxiliary layer for this vector layer.
loadDefaultStyle
loadNamedStyle Load a named style from file/local db/datasource db
mapTipTemplate The mapTip is a pretty, html representation for feature information.
maximumValue Returns the maximum value for an attribute column or an invalid variant in case of error.
minimumValue Returns the minimum value for an attribute column or an invalid variant in case of error.
modifySelection Modifies the current selection on this layer
moveVertex Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates
moveVertexV2 Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates
opacity Returns the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).
primaryKeyAttributes Returns the list of attributes which make up the layer’s primary keys.
providerType Returns the provider type for this layer
readCommonStyle
readCustomProperties
readExtentFromXml Returns true if the extent is read from the XML document when data source has no metadata, false if it’s the data provider which determines it.
readSld
readStyle Read the style for the current layer from the Dom node supplied.
readStyleManager
readSymbology Read the symbology for the current layer from the Dom node supplied.
readXml Reads vector layer specific state from project file Dom node.
receivers
referencingRelations Returns the layer’s relations, where the foreign key is on this layer.
reload Synchronises with changes in the datasource
removeExpressionField Remove an expression field
removeFieldAlias Removes an alias (a display name) for attributes to display in dialogs
removeFieldConstraint Removes a constraint for a specified field index.
removeJoin Removes a vector layer join
removeSelection Clear selection
renameAttribute Renames an attribute field (but does not commit it).
renderer Returns renderer.
resolveReferences Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
rollBack Stops a current editing operation and discards any uncommitted edits.
saveStyleToDatabase Save named and sld style of the layer to the style table in the db.
select Select feature by its ID
selectAll Select all the features
selectByExpression Select matching features using an expression.
selectByIds Select matching features using a list of feature IDs.
selectByRect Select features found within the search rectangle (in layer’s coordinates)
selectedFeatureCount Returns the number of features that are selected in this layer.
selectedFeatureIds Returns a list of the selected features IDs in this layer.
selectedFeatures Returns a copy of the user-selected features.
sender
senderSignalIndex
setAttributeTableConfig Set the attribute table configuration object.
setAuxiliaryLayer Sets the current auxiliary layer.
setConstraintExpression Set the constraint expression for the specified field index.
setCoordinateSystem Setup the coordinate system transformation for the layer
setDataSource Update the data source of the layer.
setDefaultValueDefinition Sets the definition of the expression to use when calculating the default value for a field.
setDependencies Sets the list of dependencies.
setDiagramLayerSettings
setDiagramRenderer Sets diagram rendering object (takes ownership)
setDisplayExpression Set the preview expression, used to create a human readable preview string.
setEditFormConfig Set the editFormConfig (configuration) of the form used to represent this vector layer.
setEditorWidgetSetup copydoc editorWidgetSetup
setError
setExcludeAttributesWfs A set of attributes that are not advertised in WFS requests with QGIS server.
setExcludeAttributesWms A set of attributes that are not advertised in WMS requests with QGIS server.
setExtent Sets the extent
setFeatureBlendMode Sets the blending mode used for rendering each feature
setFieldAlias Sets an alias (a display name) for attributes to display in dialogs
setFieldConstraint Sets a constraint for a specified field index.
setLabeling Set labeling configuration.
setLabelsEnabled Sets whether labels should be enabled for the layer.
setMapTipTemplate The mapTip is a pretty, html representation for feature information.
setOpacity Sets the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).
setProviderEncoding Sets the textencoding of the data provider
setReadExtentFromXml Flag 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.
setReadOnly Make layer read-only (editing disabled) or not
setRenderer Set renderer which will be invoked to represent this layer.
setSimplifyMethod Set the simplification settings for fast rendering of features
setSubsetString Set the string (typically sql) used to define a subset of the layer
setValid
simplifyDrawingCanbeApplied Returns whether the VectorLayer can apply the specified simplification hint
simplifyMethod Returns the simplification settings for fast rendering of features
sourceCrs
sourceExtent
sourceName
splitFeatures Splits features cut by the given line
splitParts Splits parts cut by the given line
startEditing Makes the layer editable.
storageType Returns the permanent storage type for this layer as a friendly name.
subsetString Returns the string (typically sql) used to define a subset of the layer.
timerEvent
translateFeature Translates feature by dx, dy
uniqueStringsMatching Returns unique string values of an attribute which contain a specified subset string.
uniqueValues Calculates a list of unique values contained within an attribute in the layer.
updateExpressionField Changes the expression used to define an expression based (virtual) field
updateExtents Update the extents for the layer.
updateFeature Updates an existing feature in the layer, replacing the attributes and geometry for the feature with matching QgsFeature.id() with the attributes and geometry from feature.
updateFields Will regenerate the fields property of this layer by obtaining all fields from the dataProvider, joined fields and virtual fields.
vectorJoins
wkbType Returns the WKBType or WKBUnknown in case of error
writeCommonStyle
writeCustomProperties
writeSld Writes the symbology of the layer into the document provided in SLD 1.1 format
writeStyle Write just the style information for the layer into the document
writeStyleManager
writeSymbology Write the symbology for the layer into the docment provided.
writeXml Write vector layer specific state to project file Dom node.

Signals

attributeAdded Will be emitted, when a new attribute has been added to this vector layer.
attributeDeleted Will be emitted, when an attribute has been deleted from this vector layer.
attributeValueChanged Is emitted whenever an attribute value change is done in the edit buffer.
beforeAddingExpressionField Will be emitted, when an expression field is going to be added to this vector layer.
beforeCommitChanges Is emitted, before changes are committed to the data provider [signal]
beforeEditingStarted Is emitted, before editing on this layer is started [signal]
beforeModifiedCheck Is emitted, when layer is checked for modifications.
beforeRemovingExpressionField Will be emitted, when an expression field is going to be deleted from this vector layer.
beforeRollBack Is emitted, before changes are rolled back [signal]
committedAttributeValuesChanges This signal is emitted, when attribute value changes are saved to the provider [signal]
committedAttributesAdded This signal is emitted, when attributes are added to the provider [signal]
committedAttributesDeleted This signal is emitted, when attributes are deleted from the provider [signal]
committedFeaturesAdded This signal is emitted, when features are added to the provider [signal]
committedFeaturesRemoved This signal is emitted, when features are deleted from the provider [signal]
committedGeometriesChanges This signal is emitted, when geometry changes are saved to the provider [signal]
displayExpressionChanged Emitted when the display expression changes
editCommandDestroyed Signal emitted, whan an edit command is destroyed
editCommandEnded Signal emitted, when an edit command successfully ended
editCommandStarted Signal emitted when a new edit command has been started
editFormConfigChanged Will be emitted whenever the edit form configuration of this layer changes.
editingStarted Is emitted, when editing on this layer has started [signal]
editingStopped Is emitted, when edited changes successfully have been written to the data provider [signal]
featureAdded Emitted when a new feature has been added to the layer
featureBlendModeChanged Signal emitted when setFeatureBlendMode() is called [signal]
featureDeleted Emitted when a feature has been deleted.
featuresDeleted Emitted when features have been deleted.
geometryChanged Is emitted whenever a geometry change is done in the edit buffer.
labelingFontNotFound Emitted when the font family defined for labeling layer is not found on system [signal]
layerModified This signal is emitted when modifications has been done on layer [signal]
mapTipTemplateChanged Emitted when the map tip changes
opacityChanged Emitted when the layer’s opacity is changed, where opacity is a value between 0 (transparent) and 1 (opaque).
raiseError Signals an error related to this vector layer.
readCustomSymbology Signal emitted whenever the symbology (QML-file) for this layer is being read.
readOnlyChanged Emitted when the read only state of this layer is changed.
selectionChanged This signal is emitted when selection was changed
subsetStringChanged Emitted when the layer’s subset string has changed.
symbolFeatureCountMapChanged Emitted when the feature count for symbols on this layer has been recalculated.
updatedFields Is emitted, whenever the fields available from this layer have been changed.
writeCustomSymbology Signal emitted whenever the symbology (QML-file) for this layer is being written.

Attributes

AddToSelection
Cross
EditFailed
EmptyGeometry
FetchFeatureFailed
IntersectSelection
InvalidLayer
NoMarker
RemoveFromSelection
SemiTransparentCircle
SetSelection
Success
AddToSelection = 1
Cross = 1
EditFailed = 2
class EditResult

Bases: int

EmptyGeometry = 1
FetchFeatureFailed = 3
IntersectSelection = 2
InvalidLayer = 4
class LayerOptions(loadDefaultStyle: bool = True, readExtentFromXml: bool = False)

Bases: sip.wrapper

Constructor for LayerOptions.

QgsVectorLayer.LayerOptions(QgsVectorLayer.LayerOptions)

loadDefaultStyle
readExtentFromXml
NoMarker = 2
RemoveFromSelection = 3
class SelectBehavior

Bases: int

SemiTransparentCircle = 0
SetSelection = 0
Success = 0
class VertexMarkerType

Bases: int

actions(self) → QgsActionManager

Returns all layer actions defined on this layer.

The pointer which is returned directly points to the actions object which is used by the layer, so any changes are immediately applied.

addAttribute(self, field: QgsField) → bool

Add an attribute field (but does not commit it) returns true if the field was added

Note

Calls to addAttribute() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addCurvedPart(self, ring: QgsCurve) → QgsGeometry.OperationResult

Note

available in Python as addCurvedPart

Note

Calls to addPart() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addCurvedRing(self, ring: QgsCurve) → Tuple[QgsGeometry.OperationResult, int]

Adds a ring to polygon/multipolygon features (takes ownership)

Parameters:
  • ring – ring to add
  • featureId – if specified, feature ID for feature ring was added to will be stored in this parameter
Returns:

QgsGeometry.OperationResult - Success - LayerNotEditable - AddRingNotInExistingFeature - InvalidInputGeometryType - AddRingNotClosed - AddRingNotValid - AddRingCrossesExistingRings

Note

available in Python as addCurvedRing

Note

Calls to addRing() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addExpressionField(self, exp: str, fld: QgsField) → int

Add a new field which is calculated by the expression specified

Parameters:
  • exp – The expression which calculates the field
  • fld – The field to calculate
Returns:

The index of the new field

New in version 2.9.

addFeature(self, feature: QgsFeature, flags: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = 0) → bool
addFeatures(self, features: object, flags: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = 0) → bool
addJoin(self, joinInfo: QgsVectorLayerJoinInfo) → bool

Joins another vector layer to this layer

Parameters:joinInfo – join object containing join layer id, target and source field

Note

since 2.6 returns bool indicating whether the join can be added *

addPart(self, ring: Iterable[QgsPointXY]) → QgsGeometry.OperationResult

Adds a new part polygon to a multipart feature

Returns:QgsGeometry.OperationResult - Success - LayerNotEditable - SelectionIsEmpty - SelectionIsGreaterThanOne - AddPartSelectedGeometryNotFound - AddPartNotMultiGeometry - InvalidBaseGeometry - InvalidInputGeometryType

Note

Calls to addPart() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addPartV2(self, ring: object) → QgsGeometry.OperationResult

Adds a new part polygon to a multipart feature

Returns:QgsGeometry.OperationResult - Success - LayerNotEditable - SelectionIsEmpty - SelectionIsGreaterThanOne - AddPartSelectedGeometryNotFound - AddPartNotMultiGeometry - InvalidBaseGeometry - InvalidInputGeometryType

Note

available in Python bindings as addPartV2

Note

Calls to addPart() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addRing(self, ring: Iterable[QgsPointXY]) → Tuple[QgsGeometry.OperationResult, int]

Adds a ring to polygon/multipolygon features

Parameters:
  • ring – ring to add
  • featureId – if specified, feature ID for feature ring was added to will be stored in this parameter
Returns:

QgsGeometry.OperationResult - Success - LayerNotEditable - AddRingNotInExistingFeature - InvalidInputGeometryType - AddRingNotClosed - AddRingNotValid - AddRingCrossesExistingRings

Note

Calls to addRing() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addTopologicalPoints(self, geom: QgsGeometry) → int

Adds topological points for every vertex of the geometry.

Parameters:geom – the geometry where each vertex is added to segments of other features
Returns:0 in case of success

Note

geom is not going to be modified by the function

Note

Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

addTopologicalPoints(self, p: QgsPointXY) -> int Adds a vertex to segments which intersect point p but don’t already have a vertex there. If a feature already has a vertex at position p, no additional vertex is inserted. This method is useful for topological editing.

Parameters:p – position of the vertex
Returns:0 in case of success

Note

Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

aggregate(self, aggregate: QgsAggregateCalculator.Aggregate, fieldOrExpression: str, parameters: QgsAggregateCalculator.AggregateParameters = QgsAggregateCalculator.AggregateParameters(), context: QgsExpressionContext = None) → Tuple[Any, bool]

Calculates an aggregated value from the layer’s features.

Parameters:
  • aggregate – aggregate to calculate
  • fieldOrExpression – source field or expression to use as basis for aggregated values.
  • parameters – parameters controlling aggregate calculation
  • context – expression context for expressions and filters
  • ok – if specified, will be set to true if aggregate calculation was successful
Returns:

calculated aggregate value

New in version 2.16.

appendError()
attributeAdded

Will be emitted, when a new attribute has been added to this vector layer. Applies only to types QgsFields.OriginEdit, QgsFields.OriginProvider and QgsFields.OriginExpression

Parameters:idx – The index of the new attribute

See also

updatedFields() [signal]

attributeAlias(self, index: int) → str

Returns the alias of an attribute name or a null string if there is no alias.

see {attributeDisplayName( int attributeIndex )} which returns the field name if no alias is defined.

attributeAliases(self) → Dict[str, str]

Returns a map of field name to attribute alias

attributeDeleted

Will be emitted, when an attribute has been deleted from this vector layer. Applies only to types QgsFields.OriginEdit, QgsFields.OriginProvider and QgsFields.OriginExpression

Parameters:idx – The index of the deleted attribute

See also

updatedFields() [signal]

attributeDisplayName(self, index: int) → str

Convenience function that returns the attribute alias if defined or the field name else

attributeList(self) → List[int]

Returns list of attribute indexes. i.e. a list from 0 … fieldCount()

attributeTableConfig(self) → QgsAttributeTableConfig

Returns the attribute table configuration object. This defines the appearance of the attribute table.

attributeValueChanged

Is emitted whenever an attribute value change is done in the edit buffer. Note that at this point the attribute change is not yet saved to the provider.

Parameters:
  • fid – The id of the changed feature
  • idx – The attribute index of the changed attribute
  • value – The new value of the attribute [signal]
auxiliaryLayer(self) → QgsAuxiliaryLayer

Returns the current auxiliary layer.

New in version 3.0.

beforeAddingExpressionField

Will be emitted, when an expression field is going to be added to this vector layer. Applies only to types QgsFields.OriginExpression

Parameters:fieldName – The name of the attribute to be added [signal]
beforeCommitChanges

Is emitted, before changes are committed to the data provider [signal]

beforeEditingStarted

Is emitted, before editing on this layer is started [signal]

beforeModifiedCheck

Is emitted, when layer is checked for modifications. Use for last-minute additions [signal]

beforeRemovingExpressionField

Will be emitted, when an expression field is going to be deleted from this vector layer. Applies only to types QgsFields.OriginExpression

Parameters:idx – The index of the attribute to be deleted [signal]
beforeRollBack

Is emitted, before changes are rolled back [signal]

beginEditCommand(self, text: str)

Create edit command for undo/redo operations

Parameters:text – text which is to be displayed in undo window
boundingBoxOfSelected(self) → QgsRectangle

Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned

capabilitiesString(self) → str

Capabilities for this layer, comma separated and translated.

changeAttributeValue(self, fid: int, field: int, newValue: Any, oldValue: Any = None, skipDefaultValues: bool = False) → bool

Changes an attribute value for a feature (but does not immediately commit the changes). The fid argument specifies the ID of the feature to be changed.

The field argument must specify a valid field index for the layer (where an index of 0 corresponds to the first field).

The new value to be assigned to the field is given by newValue.

If a valid QVariant is specified for oldValue, it will be used as the field value in the case of an undo operation corresponding to this attribute value change. If an invalid QVariant is used (the default behavior), then the feature’s current value will be automatically retrieved and used. Note that this involves a feature request to the underlying data provider, so it is more efficient to explicitly pass an oldValue if it is already available.

If skipDefaultValues is set to true, default field values will not be updated. This can be used to override default field value expressions.

Returns true if the feature’s attribute was successfully changed.

Note

Calls to changeAttributeValue() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

See also

startEditing()

See also

commitChanges()

See also

changeGeometry()

See also

updateFeature()

changeAttributeValues(self, fid: int, newValues: Dict[int, Any], oldValues: Dict[int, Any] = {}, skipDefaultValues: bool = False) → bool

Changes attributes’ values for a feature (but does not immediately commit the changes). The fid argument specifies the ID of the feature to be changed.

The new values to be assigned to the fields are given by newValues.

If a valid QVariant is specified for a field in oldValues, it will be used as the field value in the case of an undo operation corresponding to this attribute value change. If an invalid QVariant is used (the default behavior), then the feature’s current value will be automatically retrieved and used. Note that this involves a feature request to the underlying data provider, so it is more efficient to explicitly pass an oldValue if it is already available.

If skipDefaultValues is set to true, default field values will not be updated. This can be used to override default field value expressions.

Returns true if feature’s attributes was successfully changed.

Note

Calls to changeAttributeValues() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

See also

startEditing()

See also

commitChanges()

See also

changeGeometry()

See also

updateFeature()

New in version 3.0.

changeGeometry(self, fid: int, geometry: QgsGeometry, skipDefaultValue: bool = False) → bool

Changes a feature’s geometry within the layer’s edit buffer (but does not immediately commit the changes). The fid argument specifies the ID of the feature to be changed.

If skipDefaultValue is set to true, default field values will not be updated. This can be used to override default field value expressions.

Returns true if the feature’s geometry was successfully changed.

Note

Calls to changeGeometry() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

See also

startEditing()

See also

commitChanges()

See also

updateFeature()

childEvent()
clone(self) → QgsVectorLayer

Returns a new instance equivalent to this one. A new provider is created for the same data source and renderers for features and diagrams are cloned too. Moreover, each attributes (transparency, extent, selected features and so on) are identicals.

Returns:a new layer instance

New in version 3.0.

commitChanges(self) → bool

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.

See also

startEditing()

See also

commitErrors()

See also

rollBack()

commitErrors(self) → List[str]

Returns a list containing any error messages generated when attempting to commit changes to the layer.

See also

commitChanges()

committedAttributeValuesChanges

This signal is emitted, when attribute value changes are saved to the provider [signal]

committedAttributesAdded

This signal is emitted, when attributes are added to the provider [signal]

committedAttributesDeleted

This signal is emitted, when attributes are deleted from the provider [signal]

committedFeaturesAdded

This signal is emitted, when features are added to the provider [signal]

committedFeaturesRemoved

This signal is emitted, when features are deleted from the provider [signal]

committedGeometriesChanges

This signal is emitted, when geometry changes are saved to the provider [signal]

conditionalStyles(self) → QgsConditionalLayerStyles

Returns the conditional styles that are set for this layer. Style information is used to render conditional formatting in the attribute table.

Returns:Return a QgsConditionalLayerStyles object holding the conditional attribute style information. Style information is generic and can be used for anything.

New in version 2.12.

connectNotify()
constraintDescription(self, index: int) → str

Returns the descriptive name for the constraint expression for a specified field index.

New in version 3.0.

constraintExpression(self, index: int) → str

Returns the constraint expression for for a specified field index, if set.

New in version 3.0.

countSymbolFeatures(self) → QgsVectorLayerFeatureCounter

Count features for symbols. The method will return the feature counter task. You will need to connect to the symbolFeatureCountMapChanged() signal to be notified when the freshly updated feature counts are ready.

Note

If the count features for symbols has been already done a None is returned. If you need to wait for the results, you can call waitForFinished() on the feature counter.

New in version 3.0.

createExpressionContext(self) → QgsExpressionContext
createExpressionContextScope(self) → QgsExpressionContextScope
createMapRenderer(self, rendererContext: QgsRenderContext) → QgsMapLayerRenderer

Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context

New in version 2.4.

customEvent()
dataComment(self) → str

Returns a description for this layer as defined in the data provider.

dataProvider(self) → QgsVectorDataProvider
decodedSource(self, source: str, provider: str, context: QgsReadWriteContext) → str
defaultValue(self, index: int, feature: QgsFeature = QgsFeature(), context: QgsExpressionContext = None) → Any

Returns the calculated default value for the specified field index. The default value may be taken from a client side default value expression (see setDefaultValueDefinition()) or taken from the underlying data provider.

Parameters:
  • index – field index
  • feature – optional feature to use for default value evaluation. If passed, then properties from the feature (such as geometry) can be used when calculating the default value.
  • context – optional expression context to evaluate expressions again. If not specified, a default context will be created
Returns:

calculated default value

New in version 3.0.

defaultValueDefinition(self, index: int) → QgsDefaultValue

Returns the definition of the expression used when calculating the default value for a field.

Parameters:index – field index
Returns:definition of the default value with the expression evaluated when calculating default values for field, or definition with an empty string if no default is set

See also

defaultValue()

New in version 3.0.

deleteAttribute(self, attr: int) → bool

Deletes an attribute field (but does not commit it).

Note

Calls to deleteAttribute() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

deleteAttributes(self, attrs: Iterable[int]) → bool

Deletes a list of attribute fields (but does not commit it)

Parameters:attrs – the indices of the attributes to delete
Returns:true if at least one attribute has been deleted
deleteFeature(self, fid: int) → bool

Deletes a feature from the layer (but does not commit it).

Note

Calls to deleteFeature() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

deleteFeatures(self, fids: object) → bool

Deletes a set of features from the layer (but does not commit it)

Parameters:fids – The feature ids to delete
Returns:false if the layer is not in edit mode or does not support deleting in case of an active transaction depends on the provider implementation

Note

Calls to deleteFeatures() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

deleteSelectedFeatures(self) → Tuple[bool, int]

Deletes the selected features

Returns:true in case of success and false otherwise
deleteStyleFromDatabase(self, styleId: str) → Tuple[bool, str]

Delete a style from the database

Parameters:
  • styleId – the provider’s layer_styles table id of the style to delete
  • msgError – reference to string that will be updated with any error messages
Returns:

true in case of success

New in version 3.0.

deleteVertex(self, featureId: int, vertex: int) → QgsVectorLayer.EditResult

Deletes a vertex from a feature.

Parameters:
  • featureId – ID of feature to remove vertex from
  • vertex – index of vertex to delete

Note

Calls to deleteVertex() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

New in version 2.14.

dependencies(self) → Set[QgsMapLayerDependency]

Gets the list of dependencies. This includes data dependencies set by the user (setDataDependencies()) as well as dependencies given by the provider

Returns:a set of QgsMapLayerDependency

New in version 3.0.

deselect(self, featureId: int)

Deselect feature by its ID

Parameters:featureId – The id of the feature to deselect

See also

deselect()

deselect(self, featureIds: object) Deselect features by their ID

Parameters:featureIds – The ids of the features to deselect

See also

deselect()

destroyEditCommand(self)

Destroy active command and reverts all changes in it

diagramLayerSettings(self) → QgsDiagramLayerSettings
diagramRenderer(self) → QgsDiagramRenderer
diagramsEnabled(self) → bool

Returns whether the layer contains diagrams which are enabled and should be drawn.

Returns:true if layer contains enabled diagrams

New in version 2.9.

disconnectNotify()
displayExpression(self) → str

Returns the preview expression, used to create a human readable preview string. Uses QgsExpression

Returns:The expression which will be used to preview features for this layer
displayExpressionChanged

Emitted when the display expression changes

New in version 3.0: [signal]

displayField(self) → str

This is a shorthand for accessing the displayExpression if it is a simple field. If the displayExpression is more complex than a simple field, a null string will be returned.

drawVertexMarker(x: float, y: float, p: QPainter, type: QgsVectorLayer.VertexMarkerType, vertexSize: int)

Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.)

editBuffer(self) → QgsVectorLayerEditBuffer

Buffer with uncommitted editing operations. Only valid after editing has been turned on.

editCommandDestroyed

Signal emitted, whan an edit command is destroyed

Note

This is not a rollback, it is only related to the current edit command. See beforeRollBack() [signal]

editCommandEnded

Signal emitted, when an edit command successfully ended

Note

This does not mean it is also committed, only that it is written to the edit buffer. See beforeCommitChanges() [signal]

editCommandStarted

Signal emitted when a new edit command has been started

Parameters:text – Description for this edit command [signal]
editFormConfig(self) → QgsEditFormConfig

Returns the configuration of the form used to represent this vector layer. This is a writable configuration that can directly be changed in place.

Returns:The configuration of this layers’ form

New in version 2.14.

editFormConfigChanged

Will be emitted whenever the edit form configuration of this layer changes.

New in version 3.0: [signal]

editingStarted

Is emitted, when editing on this layer has started [signal]

editingStopped

Is emitted, when edited changes successfully have been written to the data provider [signal]

editorWidgetSetup(self, index: int) → QgsEditorWidgetSetup

The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field at index.

New in version 3.0.

encodedSource(self, source: str, context: QgsReadWriteContext) → str
endEditCommand(self)

Finish edit command and add it to undo/redo stack

excludeAttributesWfs(self) → Set[str]

A set of attributes that are not advertised in WFS requests with QGIS server.

excludeAttributesWms(self) → Set[str]

A set of attributes that are not advertised in WMS requests with QGIS server.

expressionField(self, index: int) → str

Returns the expression used for a given expression field

Parameters:index – An index of an epxression based (virtual) field
Returns:The expression for the field at index

New in version 2.9.

extent(self) → QgsRectangle
featureAdded

Emitted when a new feature has been added to the layer

Parameters:fid – The id of the new feature [signal]
featureBlendMode(self) → QPainter.CompositionMode

Returns the current blending mode for features

featureBlendModeChanged

Signal emitted when setFeatureBlendMode() is called [signal]

featureCount(self, legendKey: str) → int

Number of features rendered with specified legend key. Features must be first calculated by countSymbolFeatures()

Returns:number of features rendered by symbol or -1 if failed or counts are not available

featureCount(self) -> int Returns feature count including changes which have not yet been committed If you need only the count of committed features call this method on this layer’s provider.

featureDeleted

Emitted when a feature has been deleted.

If you do expensive operations in a slot connected to this, you should prefer to use featuresDeleted( const :py:class:`QgsFeatureIds`& ).

Parameters:fid – The id of the feature which has been deleted [signal]
featuresDeleted

Emitted when features have been deleted.

If features are deleted within an edit command, this will only be emitted once at the end to allow connected slots to minimize the overhead. If features are deleted outside of an edit command, this signal will be emitted once per feature.

Parameters:fids – The feature ids that have been deleted. [signal]
fieldConstraints(self, fieldIndex: int) → QgsFieldConstraints.Constraints

Returns any constraints which are present for a specified field index. These constraints may be inherited from the layer’s data provider or may be set manually on the vector layer from within QGIS.

New in version 3.0.

fieldConstraintsAndStrength(self, fieldIndex: int) → object

Returns a map of constraint with their strength for a specific field of the layer.

Parameters:fieldIndex – field index

New in version 3.0.

fields(self) → QgsFields

Returns the list of fields of this layer. This also includes fields which have not yet been saved to the provider.

Returns:A list of fields
geometryChanged

Is emitted whenever a geometry change is done in the edit buffer. Note that at this point the geometry change is not yet saved to the provider.

Parameters:
  • fid – The id of the changed feature
  • geometry – The new geometry [signal]
geometryType(self) → QgsWkbTypes.GeometryType

Returns point, line or polygon

getFeature(self, fid: int) → QgsFeature

Query the layer for the feature with the given id. If there is no such feature, the returned feature will be invalid.

getFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) → QgsFeatureIterator

Query the layer for features specified in request.

Parameters:request – feature request describing parameters of features to return
Returns:iterator for matching features from provider

getFeatures(self, expression: str) -> QgsFeatureIterator Query the layer for features matching a given expression.

getFeatures(self, fids: object) -> QgsFeatureIterator Query the layer for the features with the given ids.

getFeatures(self, rectangle: QgsRectangle) -> QgsFeatureIterator Query the layer for the features which intersect the specified rectangle.

getSelectedFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) → QgsFeatureIterator

Returns an iterator of the selected features.

Parameters:request – You may specify a request, e.g. to limit the set of requested attributes. Any filter on the request will be discarded.
Returns:Iterator over the selected features

Warning

Calling this method returns an iterator for all attributes and geometry for the selected features. Consider using the much more efficient selectedFeatureIds() or selectedFeatureCount() if you do not require access to the feature attributes or geometry.

getStyleFromDatabase(self, styleId: str) → Tuple[str, str]

Will return the named style corresponding to style id provided

hasDependencyCycle()
htmlMetadata(self) → str
insertVertex(self, x: float, y: float, atFeatureId: int, beforeVertex: int) → bool

Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature Not meaningful for Point geometries

Note

Calls to insertVertex() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

insertVertex(self, point: QgsPoint, atFeatureId: int, beforeVertex: int) -> bool Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature Not meaningful for Point geometries

Note

Calls to insertVertex() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

invertSelection(self)

Select not selected features and deselect selected ones

invertSelectionInRectangle(self, rect: QgsRectangle)

Invert selection of features found within the search rectangle (in layer’s coordinates)

Parameters:rect – The rectangle in which the selection of features will be inverted
isAuxiliaryField(self, index: int) → Tuple[bool, int]

Returns true if the field comes from the auxiliary layer, false otherwise.

New in version 3.0.

isEditCommandActive(self) → bool

Test if an edit command is active

New in version 3.0.

isEditable(self) → bool

Returns true if the provider is in editing mode

isModified(self) → bool

Returns true if the provider has been modified since the last commit

isSignalConnected()
isSpatial(self) → bool

Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeometry

joinBuffer(self) → QgsVectorLayerJoinBuffer

Returns the join buffer object.

New in version 2.14.7.

labeling(self) → QgsAbstractVectorLayerLabeling

Access to labeling configuration. May be null if labeling is not used.

Note

Labels will only be rendered if labelsEnabled() returns true.

See also

labelsEnabled()

New in version 3.0.

labelingFontNotFound

Emitted when the font family defined for labeling layer is not found on system [signal]

labelsEnabled(self) → bool

Returns whether the layer contains labels which are enabled and should be drawn.

Returns:true if layer contains enabled labels

New in version 2.9.

layerModified

This signal is emitted when modifications has been done on layer [signal]

listStylesInDatabase(self) → Tuple[int, List[str], List[str], List[str], str]

Lists all the style in db split into related to the layer and not related to

Parameters:
  • ids – the list in which will be stored the style db ids
  • names – the list in which will be stored the style names
  • descriptions – the list in which will be stored the style descriptions
  • msgError
Returns:

the number of styles related to current layer

Note

Since QGIS 3.2 Styles related to the layer are ordered with the default style first then by update time for Postgres, MySQL and Spatialite.

loadAuxiliaryLayer(self, storage: QgsAuxiliaryStorage, key: str = '') → bool

Loads the auxiliary layer for this vector layer. If there’s no corresponding table in the database, then nothing happens and false is returned. The key is optional because if this layer has been read from a XML document, then the key read in this document is used by default.

Parameters:
  • storage – The auxiliary storage where to look for the table
  • key – The key to use for joining.
Returns:

true if the auxiliary layer is well loaded, false otherwise

New in version 3.0.

loadDefaultStyle(self) → Tuple[str, bool]
loadNamedStyle(self, theURI: str, loadFromLocalDb: bool) → Tuple[str, bool]

Load a named style from file/local db/datasource db

Parameters:
  • theURI – the URI of the style or the URI of the layer
  • resultFlag – will be set to true if a named style is correctly loaded
  • loadFromLocalDb – if true forces to load from local db instead of datasource one

loadNamedStyle(self, theURI: str) -> Tuple[str, bool] Calls loadNamedStyle( theURI, resultFlag, false ); Retained for backward compatibility

mapTipTemplate(self) → str

The mapTip is a pretty, html representation for feature information.

It may also contain embedded expressions.

New in version 3.0.

mapTipTemplateChanged

Emitted when the map tip changes

New in version 3.0: [signal]

maximumValue(self, index: int) → Any

Returns the maximum value for an attribute column or an invalid variant in case of error. Note that in some circumstances when unsaved changes are present for the layer then the returned value may be outdated (for instance when the attribute value in a saved feature has been changed inside the edit buffer then the previous saved value may be returned as the maximum).

See also

minimumValue()

See also

uniqueValues()

minimumValue(self, index: int) → Any

Returns the minimum value for an attribute column or an invalid variant in case of error. Note that in some circumstances when unsaved changes are present for the layer then the returned value may be outdated (for instance when the attribute value in a saved feature has been changed inside the edit buffer then the previous saved value may be returned as the minimum).

See also

maximumValue()

See also

uniqueValues()

modifySelection(self, selectIds: object, deselectIds: object)

Modifies the current selection on this layer

Parameters:
  • selectIds – Select these ids
  • deselectIds – Deselect these ids

See also

selectByIds()

See also

deselect()

See also

deselect()

moveVertex(self, x: float, y: float, atFeatureId: int, atVertex: int) → bool

Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates

Note

Calls to moveVertex() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

moveVertexV2(self, p: QgsPoint, atFeatureId: int, atVertex: int) → bool

Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates

Note

available in Python as moveVertexV2

Note

Calls to moveVertex() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

opacity(self) → float

Returns the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).

See also

setOpacity()

See also

opacityChanged()

New in version 3.0.

opacityChanged

Emitted when the layer’s opacity is changed, where opacity is a value between 0 (transparent) and 1 (opaque).

See also

setOpacity()

See also

opacity()

New in version 3.0: [signal]

primaryKeyAttributes(self) → List[int]

Returns the list of attributes which make up the layer’s primary keys.

providerType(self) → str

Returns the provider type for this layer

raiseError

Signals an error related to this vector layer. [signal]

readCommonStyle()
readCustomProperties()
readCustomSymbology

Signal emitted whenever the symbology (QML-file) for this layer is being read. If there is custom style information saved in the file, you can connect to this signal and update the layer style accordingly.

Parameters:
  • element – The XML layer style element.
  • errorMessage – Write error messages into this string. [signal]
readExtentFromXml(self) → bool

Returns true if the extent is read from the XML document when data source has no metadata, false if it’s the data provider which determines it.

New in version 3.0.

readOnlyChanged

Emitted when the read only state of this layer is changed. Only applies to manually set readonly state, not to the edit mode.

New in version 3.0: [signal]

readSld(self, node: QDomNode, errorMessage: str) → bool
readStyle(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext) → bool

Read the style for the current layer from the Dom node supplied.

Parameters:
  • node – node that will contain the style definition for this layer.
  • errorMessage – reference to string that will be updated with any error messages
  • context – reading context (used for transform from relative to absolute paths)
Returns:

true in case of success.

readStyleManager()
readSymbology(self, layerNode: QDomNode, errorMessage: str, context: QgsReadWriteContext) → bool

Read the symbology for the current layer from the Dom node supplied.

Parameters:
  • layerNode – node that will contain the symbology definition for this layer.
  • errorMessage – reference to string that will be updated with any error messages
  • context – reading context (used for transform from relative to absolute paths)
Returns:

true in case of success.

readXml(self, layer_node: QDomNode, context: QgsReadWriteContext) → bool

Reads vector layer specific state from project file Dom node.

Note

Called by QgsMapLayer.readXml()

receivers()
referencingRelations(self, idx: int) → List[QgsRelation]

Returns the layer’s relations, where the foreign key is on this layer.

Parameters:idx – Only get relations, where idx forms part of the foreign key
Returns:A list of relations
reload(self)

Synchronises with changes in the datasource

removeExpressionField(self, index: int)

Remove an expression field

Parameters:index – The index of the field

New in version 2.6.

removeFieldAlias(self, index: int)

Removes an alias (a display name) for attributes to display in dialogs

New in version 3.0.

removeFieldConstraint(self, index: int, constraint: QgsFieldConstraints.Constraint)

Removes a constraint for a specified field index. Any constraints inherited from the layer’s data provider will be kept intact and cannot be removed.

New in version 3.0.

removeJoin(self, joinLayerId: str) → bool

Removes a vector layer join

Returns:true if join was found and successfully removed *
removeSelection(self)

Clear selection

See also

selectByIds()

renameAttribute(self, index: int, newName: str) → bool

Renames an attribute field (but does not commit it).

Parameters:
  • index – attribute index
  • newName – new name of field

Note

Calls to renameAttribute() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

New in version 2.16.

renderer(self) → QgsFeatureRenderer

Returns renderer.

resolveReferences(self, project: QgsProject)

Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.

New in version 3.0.

rollBack(self, deleteBuffer: bool = True) → bool

Stops a current editing operation and discards any uncommitted edits.

If deleteBuffer is true the editing buffer will be completely deleted (the default behavior).

See also

startEditing()

See also

commitChanges()

saveStyleToDatabase(self, name: str, description: str, useAsDefault: bool, uiFileContent: str) → str

Save named and sld style of the layer to the style table in the db.

Parameters:
  • name
  • description
  • useAsDefault
  • uiFileContent
  • msgError
select(self, featureId: int)

Select feature by its ID

Parameters:featureId – The id of the feature to select

See also

select()

select(self, featureIds: object) Select features by their ID

Parameters:featureIds – The ids of the features to select

See also

select()

selectAll(self)

Select all the features

selectByExpression(self, expression: str, behavior: QgsVectorLayer.SelectBehavior = QgsVectorLayer.SetSelection)

Select matching features using an expression.

Parameters:
  • expression – expression to evaluate to select features
  • behavior – selection type, allows adding to current selection, removing from selection, etc.

See also

selectByRect()

See also

selectByIds()

New in version 2.16.

selectByIds(self, ids: object, behavior: QgsVectorLayer.SelectBehavior = QgsVectorLayer.SetSelection)

Select matching features using a list of feature IDs. Will emit the selectionChanged() signal with the clearAndSelect flag set.

Parameters:
  • ids – feature IDs to select
  • behavior – selection type, allows adding to current selection, removing from selection, etc.

See also

selectByRect()

New in version 2.16.

selectByRect(self, rect: QgsRectangle, behavior: QgsVectorLayer.SelectBehavior = QgsVectorLayer.SetSelection)

Select features found within the search rectangle (in layer’s coordinates)

Parameters:
  • rect – search rectangle
  • behavior – selection type, allows adding to current selection, removing from selection, etc.

See also

selectByIds()

selectedFeatureCount(self) → int

Returns the number of features that are selected in this layer.

selectedFeatureIds(self) → object

Returns a list of the selected features IDs in this layer.

selectedFeatures(self) → object

Returns a copy of the user-selected features.

Warning

Calling this method triggers a request for all attributes and geometry for the selected features. Consider using the much more efficient selectedFeatureIds() or selectedFeatureCount() if you do not require access to the feature attributes or geometry.

Returns:A list of QgsFeature
selectionChanged

This signal is emitted when selection was changed

Parameters:
  • selected – Newly selected feature ids
  • deselected – Ids of all features which have previously been selected but are not any more
  • clearAndSelect – In case this is set to true, the old selection was dismissed and the new selection corresponds to selected [signal]
sender()
senderSignalIndex()
setAttributeTableConfig(self, attributeTableConfig: QgsAttributeTableConfig)

Set the attribute table configuration object. This defines the appearance of the attribute table.

setAuxiliaryLayer(self, layer: QgsAuxiliaryLayer = None)

Sets the current auxiliary layer. The auxiliary layer is automatically put in editable mode and fields are updated. Moreover, a join is created between the current layer and the auxiliary layer. Ownership is transferred.

New in version 3.0.

setConstraintExpression(self, index: int, expression: str, description: str = '')

Set the constraint expression for the specified field index. An optional descriptive name for the constraint can also be set. Setting an empty expression will clear any existing expression constraint.

New in version 3.0.

setCoordinateSystem(self)

Setup the coordinate system transformation for the layer

setDataSource(self, dataSource: str, baseName: str, provider: str, loadDefaultStyleFlag: bool = False)

Update the data source of the layer. The layer’s renderer and legend will be preserved only if the geometry type of the new data source matches the current geometry type of the layer.

Parameters:
  • dataSource – new layer data source
  • baseName – base name of the layer
  • provider – provider string
  • loadDefaultStyleFlag – set to true to reset the layer’s style to the default for the data source

New in version 2.10.

Deprecated since version Use: version with ProviderOptions argument instead

setDataSource(self, dataSource: str, baseName: str, provider: str, options: QgsDataProvider.ProviderOptions, loadDefaultStyleFlag: bool = False) Updates the data source of the layer. The layer’s renderer and legend will be preserved only if the geometry type of the new data source matches the current geometry type of the layer.

Parameters:
  • dataSource – new layer data source
  • baseName – base name of the layer
  • provider – provider string
  • options – provider options
  • loadDefaultStyleFlag – set to true to reset the layer’s style to the default for the data source

New in version 3.2.

setDefaultValueDefinition(self, index: int, definition: QgsDefaultValue)

Sets the definition of the expression to use when calculating the default value for a field.

Parameters:
  • index – field index
  • definition – default value definition to use and evaluate when calculating default values for field. Pass an empty expression to clear the default.

See also

defaultValue()

New in version 3.0.

setDependencies(self, layers: Iterable[QgsMapLayerDependency]) → bool

Sets the list of dependencies.

See also

dependencies()

Parameters:layers – set of QgsMapLayerDependency. Only user-defined dependencies will be added
Returns:false if a dependency cycle has been detected

New in version 3.0.

setDiagramLayerSettings(self, s: QgsDiagramLayerSettings)
setDiagramRenderer(self, r: QgsDiagramRenderer)

Sets diagram rendering object (takes ownership)

setDisplayExpression(self, displayExpression: str)

Set the preview expression, used to create a human readable preview string. Used e.g. in the attribute table feature list. Uses QgsExpression.

Parameters:displayExpression – The expression which will be used to preview features for this layer
setEditFormConfig(self, editFormConfig: QgsEditFormConfig)

Set the editFormConfig (configuration) of the form used to represent this vector layer.

See also

editFormConfig()

New in version 3.0.

setEditorWidgetSetup(self, index: int, setup: QgsEditorWidgetSetup)

copydoc editorWidgetSetup

setError()
setExcludeAttributesWfs(self, att: Iterable[str])

A set of attributes that are not advertised in WFS requests with QGIS server.

setExcludeAttributesWms(self, att: Iterable[str])

A set of attributes that are not advertised in WMS requests with QGIS server.

setExtent(self, rect: QgsRectangle)

Sets the extent

setFeatureBlendMode(self, blendMode: QPainter.CompositionMode)

Sets the blending mode used for rendering each feature

setFieldAlias(self, index: int, aliasString: str)

Sets an alias (a display name) for attributes to display in dialogs

New in version 3.0.

setFieldConstraint(self, index: int, constraint: QgsFieldConstraints.Constraint, strength: QgsFieldConstraints.ConstraintStrength = QgsFieldConstraints.ConstraintStrengthHard)

Sets a constraint for a specified field index. Any constraints inherited from the layer’s data provider will be kept intact and cannot be modified. Ie, calling this method only allows for new constraints to be added on top of the existing provider constraints.

New in version 3.0.

setLabeling(self, labeling: QgsAbstractVectorLayerLabeling)

Set labeling configuration. Takes ownership of the object.

New in version 3.0.

setLabelsEnabled(self, enabled: bool)

Sets whether labels should be enabled for the layer.

Note

Labels will only be rendered if labelsEnabled() is true and a labeling object is returned by labeling().

See also

labelsEnabled()

See also

labeling()

setMapTipTemplate(self, mapTipTemplate: str)

The mapTip is a pretty, html representation for feature information.

It may also contain embedded expressions.

New in version 3.0.

setOpacity(self, opacity: float)

Sets the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).

See also

opacity()

See also

opacityChanged()

New in version 3.0.

setProviderEncoding(self, encoding: str)

Sets the textencoding of the data provider

setReadExtentFromXml(self, readExtentFromXml: bool)

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

New in version 3.0.

setReadOnly(self, readonly: bool = True) → bool

Make layer read-only (editing disabled) or not

Returns:false if the layer is in editing yet
setRenderer(self, r: QgsFeatureRenderer)

Set renderer which will be invoked to represent this layer. Ownership is transferred.

setSimplifyMethod(self, simplifyMethod: QgsVectorSimplifyMethod)

Set the simplification settings for fast rendering of features

New in version 2.2.

setSubsetString(self, subset: str) → bool

Set the string (typically sql) used to define a subset of the layer

Parameters:subset – The subset string. This may be the where clause of a sql statement or other definition string specific to the underlying dataprovider and data store.
Returns:true, when setting the subset string was successful, false otherwise
setValid()
simplifyDrawingCanbeApplied(self, renderContext: QgsRenderContext, simplifyHint: QgsVectorSimplifyMethod.SimplifyHint) → bool

Returns whether the VectorLayer can apply the specified simplification hint

Note

Do not use in 3rd party code - may be removed in future version!

New in version 2.2.

simplifyMethod(self) → QgsVectorSimplifyMethod

Returns the simplification settings for fast rendering of features

New in version 2.2.

sourceCrs(self) → QgsCoordinateReferenceSystem
sourceExtent(self) → QgsRectangle
sourceName(self) → str
splitFeatures(self, splitLine: Iterable[QgsPointXY], topologicalEditing: bool = False) → QgsGeometry.OperationResult

Splits features cut by the given line

Parameters:
  • splitLine – line that splits the layer features
  • topologicalEditing – true if topological editing is enabled
Returns:

QgsGeometry.OperationResult - Success - NothingHappened - LayerNotEditable - InvalidInputGeometryType - InvalidBaseGeometry - GeometryEngineError - SplitCannotSplitPoint

Note

Calls to splitFeatures() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

splitParts(self, splitLine: Iterable[QgsPointXY], topologicalEditing: bool = False) → QgsGeometry.OperationResult

Splits parts cut by the given line

Parameters:
  • splitLine – line that splits the layer features
  • topologicalEditing – true if topological editing is enabled
Returns:

QgsGeometry.OperationResult - Success - NothingHappened - LayerNotEditable - InvalidInputGeometryType - InvalidBaseGeometry - GeometryEngineError - SplitCannotSplitPoint

Note

Calls to splitParts() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

startEditing(self) → bool

Makes the layer editable.

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

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

storageType(self) → str

Returns the permanent storage type for this layer as a friendly name. This is obtained from the data provider and does not follow any standard.

subsetString(self) → str

Returns the string (typically sql) used to define a subset of the layer.

Returns:The subset string or null QString if not implemented by the provider
subsetStringChanged

Emitted when the layer’s subset string has changed.

New in version 3.2: [signal]

symbolFeatureCountMapChanged

Emitted when the feature count for symbols on this layer has been recalculated.

New in version 3.0: [signal]

timerEvent()
translateFeature(self, featureId: int, dx: float, dy: float) → int

Translates feature by dx, dy

Parameters:
  • featureId – id of the feature to translate
  • dx – translation of x-coordinate
  • dy – translation of y-coordinate
Returns:

0 in case of success

Note

Calls to translateFeature() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

uniqueStringsMatching(self, index: int, substring: str, limit: int = -1, feedback: QgsFeedback = None) → List[str]

Returns unique string values of an attribute which contain a specified subset string. Subset matching is done in a case-insensitive manner. Note that in some circumstances when unsaved changes are present for the layer then the returned list may contain outdated values (for instance when the attribute value in a saved feature has been changed inside the edit buffer then the previous saved value will be included in the returned list).

Parameters:
  • index – column index for attribute
  • substring – substring to match (case insensitive)
  • limit – maxmum number of the values to return, or -1 to return all unique values
  • feedback – optional feedback object for canceling request
Returns:

list of unique strings containing substring

uniqueValues(self, fieldIndex: int, limit: int = -1) → Set[Any]

Calculates a list of unique values contained within an attribute in the layer. Note that in some circumstances when unsaved changes are present for the layer then the returned list may contain outdated values (for instance when the attribute value in a saved feature has been changed inside the edit buffer then the previous saved value will be included in the returned list).

Parameters:
  • fieldIndex – column index for attribute
  • limit – maximum number of values to return (or -1 if unlimited)

See also

minimumValue()

See also

maximumValue()

updateExpressionField(self, index: int, exp: str)

Changes the expression used to define an expression based (virtual) field

Parameters:
  • index – The index of the expression to change
  • exp – The new expression to set

New in version 2.9.

updateExtents(self, force: bool = False)

Update the extents for the layer. This is necessary if features are added/deleted or the layer has been subsetted.

Parameters:force – true to update layer extent even if it’s read from xml by default, false otherwise
updateFeature(self, feature: QgsFeature, skipDefaultValues: bool = False) → bool

Updates an existing feature in the layer, replacing the attributes and geometry for the feature with matching QgsFeature.id() with the attributes and geometry from feature. Changes are not immediately committed to the layer.

If skipDefaultValue is set to true, default field values will not be updated. This can be used to override default field value expressions.

Returns true if the feature’s attribute was successfully changed.

Note

Calls to updateFeature() are only valid for layers in which edits have been enabled by a call to startEditing(). Changes made to features using this method are not committed to the underlying data provider until a commitChanges() call is made. Any uncommitted changes can be discarded by calling rollBack().

Warning

This method needs to query the underlying data provider to fetch the feature with matching QgsFeature.id() on every call. Depending on the underlying data source this can be slow to execute. Consider using the more efficient changeAttributeValue() or changeGeometry() methods instead.

See also

startEditing()

See also

commitChanges()

See also

changeGeometry()

updateFields(self)

Will regenerate the fields property of this layer by obtaining all fields from the dataProvider, joined fields and virtual fields. It will also take any changes made to default values into consideration.

Note

Unless the fields on the provider have directly been modified, there is no reason to call this method.

updatedFields

Is emitted, whenever the fields available from this layer have been changed. This can be due to manually adding attributes or due to a join. [signal]

vectorJoins(self) → List[QgsVectorLayerJoinInfo]
wkbType(self) → QgsWkbTypes.Type

Returns the WKBType or WKBUnknown in case of error

writeCommonStyle()
writeCustomProperties()
writeCustomSymbology

Signal emitted whenever the symbology (QML-file) for this layer is being written. If there is custom style information you want to save to the file, you can connect to this signal and update the element accordingly.

Parameters:
  • element – The XML element where you can add additional style information to.
  • doc – The XML document that you can use to create new XML nodes.
  • errorMessage – Write error messages into this string. [signal]
writeSld(self, node: QDomNode, doc: QDomDocument, errorMessage: str, props: Dict[str, str] = {}) → bool

Writes the symbology of the layer into the document provided in SLD 1.1 format

Parameters:
  • node – the node that will have the style element added to it.
  • doc – the document that will have the QDomNode added.
  • errorMessage – reference to string that will be updated with any error messages
  • props – a open ended set of properties that can drive/inform the SLD encoding
Returns:

true in case of success

writeStyle(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext) → bool

Write just the style information for the layer into the document

Parameters:
  • node – the node that will have the style element added to it.
  • doc – the document that will have the QDomNode added.
  • errorMessage – reference to string that will be updated with any error messages
  • context – writing context (used for transform from absolute to relative paths)
Returns:

true in case of success.

writeStyleManager()
writeSymbology(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext) → bool

Write the symbology for the layer into the docment provided.

Parameters:
  • node – the node that will have the style element added to it.
  • doc – the document that will have the QDomNode added.
  • errorMessage – reference to string that will be updated with any error messages
  • context – writing context (used for transform from absolute to relative paths)
Returns:

true in case of success.

writeXml(self, layer_node: QDomNode, doc: QDomDocument, context: QgsReadWriteContext) → bool

Write vector layer specific state to project file Dom node.

Note

Called by QgsMapLayer.writeXml()