Class: QgsVectorLayer¶
- class qgis.core.QgsVectorLayer¶
Bases:
QgsMapLayer
,QgsExpressionContextGenerator
,QgsExpressionContextScopeGenerator
,QgsFeatureSink
,QgsFeatureSource
,QgsAbstractProfileSource
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 aQgsVectorDataProvider
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 by buffering layer edits until they are written to the underlyingQgsVectorDataProvider
. Before edits can be made a call tostartEditing()
is required. Any edits made to aQgsVectorLayer
are then held in memory only, and are not written to the underlyingQgsVectorDataProvider
until a call tocommitChanges()
is made. Buffered edits can be rolled back and discarded without altering the underlying provider by callingrollBack()
.Sample usage of the
QgsVectorLayer
class:uri = "point?crs=epsg:4326&field=id:integer" scratchLayer = QgsVectorLayer(uri, "Scratch point layer", "memory")
The main data providers supported by QGIS are listed below.
Vector data providers¶
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”
Since QGIS 3.4 when closing a project, the application shows a warning about potential data loss if there are any non-empty memory layers present. If your memory layer should not trigger such warning, it is possible to suppress that by setting the following custom variable:
layer.setCustomProperty("skipMemoryLayersCheck", 1)
OGR data provider (ogr)¶
Accesses data using the OGR drivers (https://gdal.org/drivers/vector/index.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.
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.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.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.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 a URI constructed using the
QgsDataSourceUri
class with the following parameters (note that parameter keys are case sensitive):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)
pageSize=number: number of features to retrieve in a single request (WFS 2)
maxNumFeatures=number: maximum number of features to retrieve (possibly across several multiple paging requests)
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’ 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.
OGC API Features data provider (oapif)¶
Used to access data provided by a OGC API - Features server.
The URI should be constructed using the
QgsDataSourceUri
class with the following parameters:url=string (mandatory): HTTP url to a OGC API - Features landing page.
typename=string (mandatory): Collection id
username=string
password=string
authcfg=string
filter=string: QGIS expression (only datetime filtering is forwarded to the server)
restrictToRequestBBOX=1: to download only features in the view extent (or more generally in the bounding box of the feature iterator)
pageSize=number: number of features to retrieve in a single request
maxNumFeatures=number: maximum number of features to retrieve (possibly across several multiple paging requests)
hideDownloadProgressDialog=1: to hide the download progress dialog.
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)’))
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 QRegularExpression 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).
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”
Grass data provider (grass)¶
Provider to display vector data in a GRASS GIS layer.
See also
QgsVectorLayer(path: str = ‘’, baseName: str = ‘’, providerLib: str = ‘’, options: QgsVectorLayer.LayerOptions = QgsVectorLayer.LayerOptions()) 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.- param path:
The path or url of the parameter. Typically this encodes parameters used by the data provider as url query items.
- param baseName:
The name used to represent the layer in the legend
- param providerLib:
The name of the data provider, e.g., “memory”, “postgres”
- param options:
layer load options
Enums
alias of
VectorEditResult
Bases:
enum.IntEnum
Bases:
enum.IntEnum
Methods
- param visitor:
Returns all layer actions defined on this layer.
Add an attribute field (but does not commit it) returns
True
if the field was addedAdds a ring to polygon/multipolygon features (takes ownership)
Add a new field which is calculated by the expression specified
- param feature:
Adds a new feature renderer
generator
to the layer.- param features:
Joins another vector layer to this layer
Adds a new part polygon to a multipart feature
Adds a new part polygon to a multipart feature
Adds a ring to polygon/multipolygon features
Adds topological points for every vertex of the geometry.
Calculates an aggregated value from the layer's features.
Add error message
Returns the alias of an attribute name or a null string if there is no alias.
Returns a map of field name to attribute alias
Convenience function that returns the attribute alias if defined or the field name else
Returns list of attribute indexes.
Returns the attribute table configuration object.
Returns the current auxiliary layer.
Create edit command for undo/redo operations
Returns the bounding box of the selected features.
Capabilities for this layer, comma separated and translated.
Changes an attribute value for a feature (but does not immediately commit the changes).
Changes attributes' values for a feature (but does not immediately commit the changes).
Changes a feature's
geometry
within the layer's edit buffer (but does not immediately commit the changes).Returns a new instance equivalent to this one.
Attempts to commit to the underlying data provider any buffered changes made since the last to call to
startEditing()
.Returns a list containing any error messages generated when attempting to commit changes to the layer.
Returns the conditional styles that are set for this layer.
Returns the descriptive name for the constraint expression for a specified field index.
Returns the constraint expression for for a specified field index, if set.
Count features for symbols.
- rtype:
QgsExpressionContext
- rtype:
QgsExpressionContextScope
Returns new instance of
QgsMapLayerRenderer
that will be used for rendering of given context- param request:
Returns a description for this layer as defined in the data provider.
- rtype:
QgsVectorDataProvider
- param source:
Returns the calculated default value for the specified field index.
Returns the definition of the expression used when calculating the default value for a field.
Deletes an attribute field (but does not commit it).
Deletes a list of attribute fields (but does not commit it)
Deletes a feature from the layer (but does not commit it).
Deletes a set of features from the layer (but does not commit it)
Deletes the selected features
Deletes a style from the database
Deletes a vertex from a feature.
Gets the list of dependencies.
Deselects feature by its ID
Destroy active command and reverts all changes in it
- rtype:
QgsDiagramLayerSettings
- rtype:
QgsDiagramRenderer
Returns whether the layer contains diagrams which are enabled and should be drawn.
Returns the preview expression, used to create a human readable preview string.
This is a shorthand for accessing the displayExpression if it is a simple field.
Draws a vertex symbol at (screen) coordinates x, y.
Buffer with uncommitted editing operations.
Returns the configuration of the form used to represent this vector layer.
The editor widget setup defines which
QgsFieldFormatter
and editor widget will be used for the field at index.- rtype:
QgsMapLayerElevationProperties
- param source:
Finish edit command and add it to undo/redo stack
A set of attributes that are not advertised in WFS requests with QGIS server.
A set of attributes that are not advertised in WMS requests with QGIS server.
Returns the expression used for a given expression field
- rtype:
QgsRectangle
Returns the current blending mode for features
Number of features rendered with specified legend key.
Returns a list of the feature renderer generators owned by the layer.
Returns any constraints which are present for a specified field index.
Returns a map of constraint with their strength for a specific field of the layer.
Returns the list of fields of this layer.
Configuration and logic to apply automatically on any edit happening on this layer.
Returns point, line or polygon
Queries the layer for the feature with the given id.
Queries the layer for features specified in request.
Queries the layer for the geometry at the given id.
Returns an iterator of the selected features.
Returns the named style corresponding to style id provided
Checks whether a new set of dependencies will introduce a cycle this method is now deprecated and always return
False
, because circular dependencies are now correctly managed.Determines if this vector layer has features.
- rtype:
bool
- rtype:
QgsFeatureSource.SpatialIndexPresence
- rtype:
str
Inserts a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature.
Invalidates the WGS84 extent.
Selects not selected features and deselects selected ones
Inverts selection of features found within the search rectangle (in layer's coordinates)
Returns
True
if the field comes from the auxiliary layer,False
otherwise.Tests if an edit command is active
Returns
True
if the provider is in editing modeReturns
True
if the provider has been modified since the last commitReturns
True
if this is a geometry layer andFalse
in case of NoGeometry (table only) or UnknownGeometryReturns
True
if the layer is a query (SQL) layer.Returns the join buffer object.
Access to labeling configuration.
Returns whether the layer contains labels which are enabled and should be drawn.
Lists all the style in db split into related to the layer and not related to
Loads the auxiliary layer for this vector layer.
- rtype:
Tuple[str, bool]
Loads a named style from file/local db/datasource db
Returns the maximum value for an attribute column or an invalid variant in case of error.
Calculates both the minimum and maximum value for an attribute column.
Returns the minimum value for an attribute column or an invalid variant in case of error.
Modifies the current selection on this layer
Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates.
Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates.
Returns the list of attributes which make up the layer's primary keys.
Read style data common to all layer types
Read custom properties from project file.
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.- param node:
- param node:
Read style manager's configuration (if any).
- param layerNode:
Reads vector layer specific state from project file Dom node.
Returns the layer's relations, where the foreign key is on this layer.
Synchronises with changes in the datasource
Removes an expression field
Removes the feature renderer with matching
id
from the layer.Removes an alias (a display name) for attributes to display in dialogs
Removes a constraint for a specified field index.
Removes a vector layer join
Clear selection
Renames an attribute field (but does not commit it).
Returns the feature renderer used for rendering the features in the layer in 2D map views.
Reselects the previous set of selected features.
Resolves references to other layers (kept as layer IDs after reading XML) into layer objects.
Stops a current editing operation and discards any uncommitted edits.
Saves named and sld style of the layer to the style table in the db.
Selects feature by its ID
Select all the features
Selects matching features using an expression.
Selects matching features using a list of feature IDs.
Selects features found within the search rectangle (in layer's coordinates)
Returns the number of features that are selected in this layer.
Returns a list of the selected features IDs in this layer.
Returns a copy of the user-selected features.
- rtype:
QgsMapLayerSelectionProperties
Sets the attribute table configuration object.
Sets the current auxiliary layer.
Sets the constraint expression for the specified field index.
Setup the coordinate system transformation for the layer
Sets the definition of the expression to use when calculating the default value for a field.
Sets the list of dependencies.
- param s:
Sets diagram rendering object (takes ownership)
Set the preview expression, used to create a human readable preview string.
Sets the
editFormConfig
(configuration) of the form used to represent this vector layer.copydoc editorWidgetSetup
Sets error message
A set of attributes that are not advertised in WFS requests with QGIS server.
A set of attributes that are not advertised in WMS requests with QGIS server.
Sets the extent
Sets the blending mode used for rendering each feature
Sets an alias (a display name) for attributes to display in dialogs
Sets a constraint for a specified field index.
Sets a split
policy
for the field with the specified index.Sets labeling configuration.
Sets whether labels should be
enabled
for the layer.Sets the text
encoding
of the data provider.Sets the
providerType
(provider key)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.
Makes layer read-only (editing disabled) or not
Sets the feature renderer which will be invoked to represent this layer in 2D map views.
Sets the simplification settings for fast rendering of features
Sets the string (typically sql) used to define a subset of the layer
Sets the coordinate transform context to
transformContext
Sets whether layer is valid or not
Returns whether the VectorLayer can apply the specified simplification hint
Returns the simplification settings for fast rendering of features
- rtype:
QgsCoordinateReferenceSystem
- rtype:
QgsRectangle
- rtype:
str
Splits features cut by the given line
Splits parts cut by the given line
Makes the layer editable.
Returns the permanent storage type for this layer as a friendly name.
Returns the manager of the stored expressions for this layer.
Returns the string (typically sql) used to define a subset of the layer.
Returns whether the layer supports editing or not
Ids of features rendered with specified legend key.
- rtype:
QgsMapLayerTemporalProperties
Translates feature by dx, dy
Returns unique string values of an attribute which contain a specified subset string.
Calculates a list of unique values contained within an attribute in the layer.
Changes the expression used to define an expression based (virtual) field
Update the extents for the layer.
Updates an existing
feature
in the layer, replacing the attributes and geometry for the feature with matchingQgsFeature.id()
with the attributes and geometry fromfeature
.Will regenerate the fields property of this layer by obtaining all fields from the dataProvider, joined fields and virtual fields.
- rtype:
List[QgsVectorLayerJoinInfo]
Returns the vector layer type flags.
Returns the WKBType or WKBUnknown in case of error
Write style data common to all layer types
Write custom properties to project file.
Writes the symbology of the layer into the document provided in SLD 1.1 format
- param node:
Write style manager's configuration (if exists).
- param node:
Writes vector layer specific state to project file Dom node.
Signals
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL
- class DeleteContext(cascade: bool = False, project: QgsProject = None)¶
Bases:
sip.wrapper
Constructor for DeleteContext.
QgsVectorLayer.DeleteContext(QgsVectorLayer.DeleteContext)
- cascade¶
- handledFeatures(self, layer: QgsVectorLayer) object ¶
Returns a list of feature IDs from the specified
layer
affected by the delete operation.- Parameters:
layer (QgsVectorLayer) –
- Return type:
object
- handledLayers(self, includeAuxiliaryLayers: bool = True) List[QgsVectorLayer] ¶
Returns a list of all layers affected by the delete operation.
If
includeAuxiliaryLayers
isFalse
then auxiliary layers will not be included in the returned list.- Parameters:
includeAuxiliaryLayers (bool = True) –
- Return type:
List[QgsVectorLayer]
- project¶
- EditResult¶
alias of
VectorEditResult
- class LayerOptions(loadDefaultStyle: bool = True, readExtentFromXml: bool = False)¶
Bases:
sip.wrapper
Constructor for LayerOptions.
QgsVectorLayer.LayerOptions(transformContext:
QgsCoordinateTransformContext
, loadDefaultStyle: bool = True, readExtentFromXml: bool = False) Constructor for LayerOptions.New in version 3.8.
QgsVectorLayer.LayerOptions(QgsVectorLayer.LayerOptions)
- fallbackCrs¶
- fallbackWkbType¶
- forceReadOnly¶
- loadAllStoredStyles¶
- loadDefaultStyle¶
- readExtentFromXml¶
- skipCrsValidation¶
- transformContext¶
- class SelectBehavior(value)¶
Bases:
enum.IntEnum
Specifies how a selection should be applied.
New in version 3.22.
SetSelection
: Set selection, removing any existing selectionAddToSelection
: Add selection to current selectionIntersectSelection
: Modify current selection to include only select features which matchRemoveFromSelection
: Remove from current selection
- class VertexMarkerType(value)¶
Bases:
enum.IntEnum
Editing vertex markers, used for showing vertices during a edit operation.
New in version 3.22.
SemiTransparentCircle
: Semi-transparent circle markerCross
: Cross markerNoMarker
: No marker
- accept(self, visitor: QgsStyleEntityVisitorInterface) bool ¶
- Parameters:
visitor (QgsStyleEntityVisitorInterface) –
- Return type:
bool
- 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.
- Return type:
- addAttribute(self, field: QgsField) bool ¶
Add an attribute field (but does not commit it) returns
True
if the field was addedNote
Calls to
addAttribute()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
field (QgsField) –
- Return type:
bool
- addCurvedPart(self, ring: QgsCurve) Qgis.GeometryOperationResult ¶
Note
available in Python as addCurvedPart
Note
Calls to
addPart()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
ring (QgsCurve) –
- Return type:
- addCurvedRing(self, ring: QgsCurve) Tuple[Qgis.GeometryOperationResult, int] ¶
Adds a ring to polygon/multipolygon features (takes ownership)
- Parameters:
ring (QgsCurve) – ring to add
featureId – if specified, feature ID for feature ring was added to will be stored in this parameter
- Return type:
Tuple[Qgis.GeometryOperationResult, int]
- Returns:
Qgis
.GeometryOperationResultSuccess
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.
- addExpressionField(self, exp: str, fld: QgsField) int ¶
Add a new field which is calculated by the expression specified
- Parameters:
exp (str) – The expression which calculates the field
fld (QgsField) – The field to calculate
- Return type:
int
- Returns:
The index of the new field
New in version 2.9.
- addFeature(self, feature: QgsFeature, flags: QgsFeatureSink.Flags | QgsFeatureSink.Flag = QgsFeatureSink.Flags()) bool ¶
- Parameters:
feature (QgsFeature) –
flags (Union[QgsFeatureSink.Flags) –
- Return type:
bool
- addFeatureRendererGenerator(self, generator: QgsFeatureRendererGenerator)¶
Adds a new feature renderer
generator
to the layer.Ownership of
generator
is transferred to the layer.See also
See also
New in version 3.18.
- Parameters:
generator (QgsFeatureRendererGenerator) –
- addFeatures(self, features: Iterable[QgsFeature], flags: QgsFeatureSink.Flags | QgsFeatureSink.Flag = QgsFeatureSink.Flags()) bool ¶
- Parameters:
features (Iterable[QgsFeature]) –
flags (Union[QgsFeatureSink.Flags) –
- Return type:
bool
- addJoin(self, joinInfo: QgsVectorLayerJoinInfo) bool ¶
Joins another vector layer to this layer
- Parameters:
joinInfo (QgsVectorLayerJoinInfo) – join object containing join layer id, target and source field
Note
since 2.6 returns bool indicating whether the join can be added
- Return type:
bool
- addPart(self, ring: Iterable[QgsPointXY]) Qgis.GeometryOperationResult ¶
Adds a new part polygon to a multipart feature
- Return type:
- Returns:
Qgis
.GeometryOperationResultSuccess
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.- Parameters:
ring (Iterable[QgsPointXY]) –
- addPartV2(self, ring: Iterable[QgsPointXY]) Qgis.GeometryOperationResult ¶
Adds a new part polygon to a multipart feature
- Returns:
Qgis
.GeometryOperationResultSuccess
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.addPartV2(self, ring: Iterable[QgsPoint]) -> Qgis.GeometryOperationResult Adds a new part polygon to a multipart feature
- Return type:
- Returns:
Qgis
.GeometryOperationResultSuccess
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
ring (Iterable[QgsPointXY]) –
- addRing(self, ring: Iterable[QgsPointXY]) Tuple[Qgis.GeometryOperationResult, int] ¶
Adds a ring to polygon/multipolygon features
- Parameters:
ring (Iterable[QgsPointXY]) – ring to add
featureId – if specified, feature ID for feature ring was added to will be stored in this parameter
- Returns:
Qgis
.GeometryOperationResultSuccess
LayerNotEditable
AddRingNotInExistingFeature
InvalidInputGeometryType
AddRingNotClosed
AddRingNotValid
AddRingCrossesExistingRings
Note
Calls to
addRing()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.addRing(self, ring: Iterable[QgsPoint]) -> Tuple[Qgis.GeometryOperationResult, 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
- Return type:
Tuple[Qgis.GeometryOperationResult, int]
- Returns:
Qgis
.GeometryOperationResultSuccess
LayerNotEditable
AddRingNotInExistingFeature
InvalidInputGeometryType
AddRingNotClosed
AddRingNotValid
AddRingCrossesExistingRings
Note
Calls to
addRing()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.
- addTopologicalPoints(self, geom: QgsGeometry) int ¶
Adds topological points for every vertex of the geometry.
- Parameters:
geom (QgsGeometry) – the geometry where each vertex is added to segments of other features
- Returns:
-1 in case of layer error (invalid or non editable)
- Returns:
0 in case of success
- Returns:
1 in case of geometry error (non spatial or null geometry)
- Returns:
2 in case no vertices needed to be added
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.addTopologicalPoints(self, p:
QgsPointXY
) -> int Adds a vertex to segments which intersect pointp
but don’t already have a vertex there. If a feature already has a vertex at positionp
, no additional vertex is inserted. This method is useful for topological editing.- Parameters:
p – position of the vertex
- Returns:
-1 in case of layer error (invalid or non editable)
- Returns:
0 in case of success
- Returns:
1 in case of geometry error (non spatial or null geometry)
- Returns:
2 in case no vertices needed to be added
Note
Calls to
addTopologicalPoints()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.addTopologicalPoints(self, p:
QgsPoint
) -> int Adds a vertex to segments which intersect pointp
but don’t already have a vertex there. If a feature already has a vertex at positionp
, no additional vertex is inserted. This method is useful for topological editing.- Parameters:
p – position of the vertex
- Returns:
-1 in case of layer error (invalid or non editable)
- Returns:
0 in case of success
- Returns:
1 in case of geometry error (non spatial or null geometry)
- Returns:
2 in case no vertices needed to be added
Note
Calls to
addTopologicalPoints()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.New in version 3.10.
addTopologicalPoints(self, ps: Iterable[QgsPoint]) -> int Adds a vertex to segments which intersect any of the points
p
but don’t already have a vertex there. If a feature already has a vertex at positionp
, no additional vertex is inserted. This method is useful for topological editing.- Parameters:
ps – point sequence of the vertices
- Returns:
-1 in case of layer error (invalid or non editable)
- Returns:
0 in case of success
- Returns:
1 in case of geometry error (non spatial or null geometry)
- Return type:
int
- Returns:
2 in case no vertices needed to be added
Note
Calls to
addTopologicalPoints()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.New in version 3.16.
- afterCommitChanges¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- afterRollBack¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- aggregate(self, aggregate: QgsAggregateCalculator.Aggregate, fieldOrExpression: str, parameters: QgsAggregateCalculator.AggregateParameters = QgsAggregateCalculator.AggregateParameters(), context: QgsExpressionContext = None, fids: object = None, feedback: QgsFeedback = None) Tuple[Any, bool] ¶
Calculates an aggregated value from the layer’s features. Currently any filtering expression provided will override filters in the FeatureRequest.
- Parameters:
aggregate (QgsAggregateCalculator.Aggregate) – aggregate to calculate
fieldOrExpression (str) – source field or expression to use as basis for aggregated values.
parameters (QgsAggregateCalculator.AggregateParameters = QgsAggregateCalculator.AggregateParameters()) – parameters controlling aggregate calculation
context (
QgsExpressionContext
= None) – expression context for expressions and filtersok – if specified, will be set to
True
if aggregate calculation was successfulfids (object = None) – list of fids to filter, otherwise will use all fids
feedback (
QgsFeedback
= None) – optional feedback argument for early cancellation (since QGIS 3.22)
- Return type:
Tuple[Any, bool]
- Returns:
calculated aggregate value
New in version 2.16.
- allowCommitChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- appendError(self, error: QgsErrorMessage)¶
Add error message
- attributeAdded¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
- Parameters:
index (int) –
- Return type:
str
- attributeAliases(self) Dict[str, str] ¶
Returns a map of field name to attribute alias
- Return type:
Dict[str, str]
- attributeDeleted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- attributeDisplayName(self, index: int) str ¶
Convenience function that returns the attribute alias if defined or the field name else
- Parameters:
index (int) –
- Return type:
str
- attributeList(self) List[int] ¶
Returns list of attribute indexes. i.e. a list from 0 …
fieldCount()
- Return type:
List[int]
- attributeTableConfig(self) QgsAttributeTableConfig ¶
Returns the attribute table configuration object. This defines the appearance of the attribute table.
- Return type:
- attributeValueChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- auxiliaryLayer(self) QgsAuxiliaryLayer ¶
Returns the current auxiliary layer.
New in version 3.0.
- Return type:
- beforeAddingExpressionField¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beforeCommitChanges¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beforeEditingStarted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beforeModifiedCheck¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beforeRemovingExpressionField¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beforeRollBack¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- beginEditCommand(self, text: str)¶
Create edit command for undo/redo operations
- Parameters:
text (str) – 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
- Return type:
- capabilitiesString(self) str ¶
Capabilities for this layer, comma separated and translated.
- Return type:
str
- 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 anoldValue
if it is already available.If
skipDefaultValues
is set toTrue
, default field values will not be updated. This can be used to override default field value expressions.- Return type:
bool
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.See also
See also
See also
See also
- Parameters:
fid (int) –
field (int) –
newValue (Any) –
oldValue (Any = None) –
skipDefaultValues (bool = False) –
- 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 toTrue
, default field values will not be updated. This can be used to override default field value expressions.- Return type:
bool
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.See also
See also
See also
See also
See also
New in version 3.0.
- Parameters:
fid (int) –
newValues (Dict[int) –
oldValues (Dict[int) –
skipDefaultValues (bool = False) –
- 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). Thefid
argument specifies the ID of the feature to be changed.If
skipDefaultValue
is set toTrue
, default field values will not be updated. This can be used to override default field value expressions.- Return type:
bool
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.See also
See also
See also
See also
- Parameters:
fid (int) –
geometry (QgsGeometry) –
skipDefaultValue (bool = False) –
- childEvent(self, QChildEvent)¶
- 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 identical.
- Return type:
- Returns:
a new layer instance
New in version 3.0.
- commitChanges(self, stopEditing: bool = True) 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.By setting
stopEditing
toFalse
, the layer will stay in editing mode. Otherwise the layer editing mode will be disabled if the commit is successful.See also
See also
See also
- Parameters:
stopEditing (bool = True) –
- Return type:
bool
- commitErrors(self) List[str] ¶
Returns a list containing any error messages generated when attempting to commit changes to the layer.
See also
- Return type:
List[str]
- committedAttributeValuesChanges¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- committedAttributesAdded¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- committedAttributesDeleted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- committedFeaturesAdded¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- committedFeaturesRemoved¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- committedGeometriesChanges¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
- Return type:
- 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(self, QMetaMethod)¶
- constraintDescription(self, index: int) str ¶
Returns the descriptive name for the constraint expression for a specified field index.
See also
See also
See also
New in version 3.0.
- Parameters:
index (int) –
- Return type:
str
- constraintExpression(self, index: int) str ¶
Returns the constraint expression for for a specified field index, if set.
See also
See also
See also
New in version 3.0.
- Parameters:
index (int) –
- Return type:
str
- countSymbolFeatures(self, storeSymbolFids: bool = False) 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.- Parameters:
storeSymbolFids (bool = False) – If
True
will gather the feature ids (fids) per symbol, otherwise only the count. DefaultFalse
.
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 callwaitForFinished()
on the feature counter.New in version 3.0.
- Return type:
- createExpressionContext(self) QgsExpressionContext ¶
- Return type:
- createExpressionContextScope(self) QgsExpressionContextScope ¶
- Return type:
- createMapRenderer(self, rendererContext: QgsRenderContext) QgsMapLayerRenderer ¶
Returns new instance of
QgsMapLayerRenderer
that will be used for rendering of given contextNew in version 2.4.
- Parameters:
rendererContext (QgsRenderContext) –
- Return type:
- createProfileGenerator(self, request: QgsProfileRequest) QgsAbstractProfileGenerator ¶
- Parameters:
request (QgsProfileRequest) –
- Return type:
- customEvent(self, QEvent)¶
- dataComment(self) str ¶
Returns a description for this layer as defined in the data provider.
- Return type:
str
- dataProvider(self) QgsVectorDataProvider ¶
- Return type:
- decodedSource(self, source: str, provider: str, context: QgsReadWriteContext) str ¶
- Parameters:
source (str) –
provider (str) –
context (QgsReadWriteContext) –
- Return type:
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 (int) – field index
feature (
QgsFeature
= QgsFeature()) – 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 (
QgsExpressionContext
= None) – optional expression context to evaluate expressions again. If not specified, a default context will be created
- Return type:
Any
- Returns:
calculated default value
See also
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 (int) – field index
- Return type:
- 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
See also
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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
attr (int) –
- Return type:
bool
- deleteAttributes(self, attrs: Iterable[int]) bool ¶
Deletes a list of attribute fields (but does not commit it)
- Parameters:
attrs (Iterable[int]) – the indices of the attributes to delete
- Return type:
bool
- Returns:
True
if at least one attribute has been deleted
- deleteFeature(self, fid: int, context: QgsVectorLayer.DeleteContext = None) bool ¶
Deletes a feature from the layer (but does not commit it).
- Parameters:
fid (int) – The feature id to delete
context (QgsVectorLayer.DeleteContext = None) – The chain of features who will be deleted for feedback and to avoid endless recursions
Note
Calls to
deleteFeature()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Return type:
bool
- deleteFeatures(self, fids: object, context: QgsVectorLayer.DeleteContext = None) bool ¶
Deletes a set of features from the layer (but does not commit it)
- Parameters:
fids (object) – The feature ids to delete
context (QgsVectorLayer.DeleteContext = None) – The chain of features who will be deleted for feedback and to avoid endless recursions
- Return type:
bool
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.
- deleteSelectedFeatures(self, context: QgsVectorLayer.DeleteContext = None) Tuple[bool, int] ¶
Deletes the selected features
- Parameters:
deletedCount – The number of successfully deleted features
context (QgsVectorLayer.DeleteContext = None) – The chain of features who will be deleted for feedback and to avoid endless recursions
- Return type:
Tuple[bool, int]
- Returns:
True
in case of success andFalse
otherwise
- deleteStyleFromDatabase(self, styleId: str) Tuple[bool, str] ¶
Deletes a style from the database
- Parameters:
styleId (str) – the provider’s layer_styles table id of the style to delete
- Return type:
Tuple[bool, str]
- Returns:
True
in case of successmsgError: will be set to a descriptive error message if any occurs
New in version 3.0.
- deleteVertex(self, featureId: int, vertex: int) Qgis.VectorEditResult ¶
Deletes a vertex from a feature.
- Parameters:
featureId (int) – ID of feature to remove vertex from
vertex (int) – index of vertex to delete
Note
Calls to
deleteVertex()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.New in version 2.14.
- Return type:
- 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- Return type:
- Returns:
a set of
QgsMapLayerDependency
New in version 3.0.
- deselect(self, featureId: int)¶
Deselects feature by its ID
- Parameters:
featureId (int) – The id of the feature to deselect
See also
deselect(self, featureIds: object) Deselects features by their ID
- Parameters:
featureIds – The ids of the features to deselect
See also
- destroyEditCommand(self)¶
Destroy active command and reverts all changes in it
- diagramLayerSettings(self) QgsDiagramLayerSettings ¶
- Return type:
- diagramRenderer(self) QgsDiagramRenderer ¶
- Return type:
- diagramsEnabled(self) bool ¶
Returns whether the layer contains diagrams which are enabled and should be drawn.
- Return type:
bool
- Returns:
True
if layer contains enabled diagrams
New in version 2.9.
- disconnectNotify(self, QMetaMethod)¶
- displayExpression(self) str ¶
Returns the preview expression, used to create a human readable preview string. Uses
QgsExpression
- Return type:
str
- Returns:
The expression which will be used to preview features for this layer
- displayExpressionChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
See also
- Return type:
str
- drawVertexMarker(x: float, y: float, p: QPainter, type: Qgis.VertexMarkerType, vertexSize: int)¶
Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.)
Deprecated since version Use: the equivalent
QgsSymbolLayerUtils
.drawVertexMarker function instead- Parameters:
x (float) –
y (float) –
p (QPainter) –
type (Qgis.VertexMarkerType) –
vertexSize (int) –
- editBuffer(self) QgsVectorLayerEditBuffer ¶
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
- Return type:
- editCommandDestroyed¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- editCommandEnded¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- editCommandStarted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- editFormConfig(self) QgsEditFormConfig ¶
Returns the configuration of the form used to represent this vector layer.
- Return type:
- Returns:
The configuration of this layers’ form
New in version 2.14.
- editFormConfigChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
- Parameters:
index (int) –
- Return type:
- elevationProperties(self) QgsMapLayerElevationProperties ¶
- Return type:
- encodedSource(self, source: str, context: QgsReadWriteContext) str ¶
- Parameters:
source (str) –
context (QgsReadWriteContext) –
- Return type:
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.
Deprecated since version QGIS: 3.16 use
fields()
.configurationFlags() instead- Return type:
Set[str]
- excludeAttributesWms(self) Set[str] ¶
A set of attributes that are not advertised in WMS requests with QGIS server.
Deprecated since version QGIS: 3.16 use
fields()
.configurationFlags() instead- Return type:
Set[str]
- expressionField(self, index: int) str ¶
Returns the expression used for a given expression field
- Parameters:
index (int) – An index of an epxression based (virtual) field
- Return type:
str
- Returns:
The expression for the field at index
New in version 2.9.
- extent(self) QgsRectangle ¶
- Return type:
- featureAdded¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- featureBlendMode(self) QPainter.CompositionMode ¶
Returns the current blending mode for features
- Return type:
QPainter.CompositionMode
- featureBlendModeChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
- Return type:
int
- Returns:
the number of features on this layer or -1 if unknown.
- Parameters:
legendKey (str) –
- featureDeleted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- featureRendererGenerators(self) List[QgsFeatureRendererGenerator] ¶
Returns a list of the feature renderer generators owned by the layer.
See also
See also
New in version 3.18.
- Return type:
- featuresDeleted¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
See also
New in version 3.0.
- Parameters:
fieldIndex (int) –
- Return type:
- fieldConstraintsAndStrength(self, fieldIndex: int) Dict[QgsFieldConstraints.Constraint, QgsFieldConstraints.ConstraintStrength] ¶
Returns a map of constraint with their strength for a specific field of the layer.
- Parameters:
fieldIndex (int) – field index
New in version 3.0.
- Return type:
Dict[QgsFieldConstraints.Constraint, QgsFieldConstraints.ConstraintStrength]
- fields(self) QgsFields ¶
Returns the list of fields of this layer. This also includes fields which have not yet been saved to the provider.
- Return type:
- Returns:
A list of fields
- geometryChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- geometryOptions(self) QgsGeometryOptions ¶
Configuration and logic to apply automatically on any edit happening on this layer.
New in version 3.4.
- Return type:
- geometryType(self) Qgis.GeometryType ¶
Returns point, line or polygon
- Return type:
- getFeature(self, fid: int) QgsFeature ¶
Queries the layer for the feature with the given id. If there is no such feature, the returned feature will be invalid.
- Parameters:
fid (int) –
- Return type:
- getFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) QgsFeatureIterator ¶
Queries the layer for features specified in request.
- Parameters:
request (
QgsFeatureRequest
= QgsFeatureRequest()) – feature request describing parameters of features to return- Return type:
- Returns:
iterator for matching features from provider
getFeatures(self, expression: str) -> QgsFeatureIterator Queries the layer for features matching a given expression.
getFeatures(self, fids: object) -> QgsFeatureIterator Queries the layer for the features with the given ids.
getFeatures(self, rectangle:
QgsRectangle
) -> QgsFeatureIterator Queries the layer for the features which intersect the specified rectangle.
- getGeometry(self, fid: int) QgsGeometry ¶
Queries the layer for the geometry at the given id. If there is no such feature, the returned geometry will be invalid.
- Parameters:
fid (int) –
- Return type:
- getSelectedFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) QgsFeatureIterator ¶
Returns an iterator of the selected features.
- Parameters:
request (
QgsFeatureRequest
= QgsFeatureRequest()) – You may specify a request, e.g. to limit the set of requested attributes. Any filter on the request will be discarded.- Return type:
- 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()
orselectedFeatureCount()
if you do not require access to the feature attributes or geometry.See also
See also
- getStyleFromDatabase(self, styleId: str) Tuple[str, str] ¶
Returns the named style corresponding to style id provided
- Parameters:
styleId (str) –
- Return type:
Tuple[str, str]
- hasDependencyCycle(self, Iterable[QgsMapLayerDependency]) bool ¶
Checks whether a new set of dependencies will introduce a cycle this method is now deprecated and always return
False
, because circular dependencies are now correctly managed.Deprecated since version QGIS: 3.10
- hasFeatures(self) QgsFeatureSource.FeatureAvailability ¶
Determines if this vector layer has features.
Warning
when a layer is editable and some features have been deleted, this will return
QgsFeatureSource
.FeatureAvailability.FeaturesMayBeAvailable to avoid a potentially expensive call to the dataprovider.New in version 3.4.
- Return type:
- hasMapTips(self) bool ¶
- Return type:
bool
- hasSpatialIndex(self) QgsFeatureSource.SpatialIndexPresence ¶
- Return type:
- htmlMetadata(self) str ¶
- Return type:
str
- insertVertex(self, x: float, y: float, atFeatureId: int, beforeVertex: int) bool ¶
Inserts 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.insertVertex(self, point:
QgsPoint
, atFeatureId: int, beforeVertex: int) -> bool Inserts 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
x (float) –
y (float) –
atFeatureId (int) –
beforeVertex (int) –
- Return type:
bool
- invalidateWgs84Extent(self)¶
Invalidates the WGS84 extent. If FlagTrustLayerMetadata is enabled, the extent is not invalidated because we want to trust metadata whatever happens.
New in version 3.20.
- invertSelection(self)¶
Selects not selected features and deselects selected ones
- invertSelectionInRectangle(self, rect: QgsRectangle)¶
Inverts selection of features found within the search rectangle (in layer’s coordinates)
- Parameters:
rect (QgsRectangle) – The rectangle in which the selection of features will be inverted
See also
- isAuxiliaryField(self, index: int) Tuple[bool, int] ¶
Returns
True
if the field comes from the auxiliary layer,False
otherwise.New in version 3.0.
- Parameters:
index (int) –
- Return type:
Tuple[bool, int]
- isEditCommandActive(self) bool ¶
Tests if an edit command is active
New in version 3.0.
- Return type:
bool
- isEditable(self) bool ¶
Returns
True
if the provider is in editing mode- Return type:
bool
- isModified(self) bool ¶
Returns
True
if the provider has been modified since the last commit- Return type:
bool
- isSignalConnected(self, QMetaMethod) bool ¶
- isSpatial(self) bool ¶
Returns
True
if this is a geometry layer andFalse
in case of NoGeometry (table only) or UnknownGeometry- Return type:
bool
- isSqlQuery(self) bool ¶
Returns
True
if the layer is a query (SQL) layer.Note
this is simply a shortcut to check if the SqlQuery flag is set.
See also
New in version 3.24.
- Return type:
bool
- joinBuffer(self) QgsVectorLayerJoinBuffer ¶
Returns the join buffer object.
New in version 2.14.7.
- Return type:
- labeling(self) QgsAbstractVectorLayerLabeling ¶
Access to labeling configuration. May be
None
if labeling is not used.Note
Labels will only be rendered if
labelsEnabled()
returnsTrue
.See also
New in version 3.0.
- Return type:
- labelingFontNotFound¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- labelsEnabled(self) bool ¶
Returns whether the layer contains labels which are enabled and should be drawn.
- Return type:
bool
- Returns:
True
if layer contains enabled labels
See also
New in version 2.9.
- 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
- Return type:
Tuple[int, List[str], List[str], List[str], str]
- Returns:
the number of styles related to current layer (-1 on not implemented)
descriptions: the list in which will be stored the style descriptions
msgError: will be set to a descriptive error message if any occurs
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 (QgsAuxiliaryStorage) – The auxiliary storage where to look for the table
key (str = '') – The key to use for joining.
- Return type:
bool
- Returns:
True
if the auxiliary layer is well loaded,False
otherwise
New in version 3.0.
- loadDefaultStyle(self) Tuple[str, bool] ¶
- Return type:
Tuple[str, bool]
- loadNamedStyle(self, theURI: str, loadFromLocalDb: bool, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) Tuple[str, bool] ¶
Loads a named style from file/local db/datasource db
- Parameters:
theURI (str) – the URI of the style or the URI of the layer
resultFlag – will be set to
True
if a named style is correctly loadedloadFromLocalDb (bool) – if
True
forces to load from local db instead of datasource onecategories (Union[QgsMapLayer.StyleCategories) – the style categories to be loaded.
loadNamedStyle(self, theURI: str, categories: Union[QgsMapLayer.StyleCategories, QgsMapLayer.StyleCategory] = QgsMapLayer.AllStyleCategories) -> Tuple[str, bool] Calls loadNamedStyle( theURI, resultFlag,
False
); Retained for backward compatibility- Return type:
Tuple[str, bool]
- maximumValue(self, index: int) Any ¶
Returns the maximum value for an attribute column or an invalid variant in case of error.
Note
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).
Note
If both the minimum and maximum value are required it is more efficient to call
minimumAndMaximumValue()
instead of separate calls tominimumValue()
andmaximumValue()
.See also
See also
See also
- Parameters:
index (int) –
- Return type:
Any
- minimumAndMaximumValue(self, index: int) Tuple[Any, Any] ¶
Calculates both the minimum and maximum value for an attribute column.
This is more efficient then calling both
minimumValue()
andmaximumValue()
when both the minimum and maximum values are required.- Parameters:
index (int) – index of field to calculate minimum and maximum value for.
Note
In some circumstances when unsaved changes are present for the layer then the calculated values 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
See also
- Return type:
Tuple[Any, Any]
- Returns:
minimum: will be set to minimum attribute value or an invalid variant in case of error.
maximum: will be set to maximum attribute value or an invalid variant in case of error.
New in version 3.20.
- minimumValue(self, index: int) Any ¶
Returns the minimum value for an attribute column or an invalid variant in case of error.
Note
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).
Note
If both the minimum and maximum value are required it is more efficient to call
minimumAndMaximumValue()
instead of separate calls tominimumValue()
andmaximumValue()
.See also
See also
See also
- Parameters:
index (int) –
- Return type:
Any
- modifySelection(self, selectIds: object, deselectIds: object)¶
Modifies the current selection on this layer
- Parameters:
selectIds (object) – Select these ids
deselectIds (object) – Deselect these ids
See also
See also
See also
See also
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
x (float) –
y (float) –
atFeatureId (int) –
atVertex (int) –
- Return type:
bool
- 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.- Parameters:
p (QgsPoint) –
atFeatureId (int) –
atVertex (int) –
- Return type:
bool
- primaryKeyAttributes(self) List[int] ¶
Returns the list of attributes which make up the layer’s primary keys.
- Return type:
List[int]
- raiseError¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- readCommonStyle(self, layerElement: QDomElement, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories)¶
Read style data common to all layer types
New in version 3.0.
- readCustomProperties(self, layerNode: QDomNode, keyStartsWith: str = '')¶
Read custom properties from project file.
- Parameters:
layerNode – note to read from
keyStartsWith – reads only properties starting with the specified string (or all if the string is empty)
- readCustomSymbology¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_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.
- Return type:
bool
- readOnlyChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- readSld(self, node: QDomNode, errorMessage: str) bool ¶
- Parameters:
node (QDomNode) –
errorMessage (str) –
- Return type:
bool
- readStyle(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool ¶
- Parameters:
node (QDomNode) –
errorMessage (str) –
context (QgsReadWriteContext) –
categories (Union[QgsMapLayer.StyleCategories) –
- Return type:
bool
- readStyleManager(self, layerNode: QDomNode)¶
Read style manager’s configuration (if any). To be called by subclasses.
- readSymbology(self, layerNode: QDomNode, errorMessage: str, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool ¶
- Parameters:
layerNode (QDomNode) –
errorMessage (str) –
context (QgsReadWriteContext) –
categories (Union[QgsMapLayer.StyleCategories) –
- Return type:
bool
- readXml(self, layer_node: QDomNode, context: QgsReadWriteContext) bool ¶
Reads vector layer specific state from project file Dom node.
Note
Called by
QgsMapLayer.readXml()
.- Parameters:
layer_node (QDomNode) –
context (QgsReadWriteContext) –
- Return type:
bool
- receivers(self, PYQT_SIGNAL) int ¶
- referencingRelations(self, idx: int) List[QgsRelation] ¶
Returns the layer’s relations, where the foreign key is on this layer.
- Parameters:
idx (int) – Only get relations, where idx forms part of the foreign key
- Return type:
List[QgsRelation]
- Returns:
A list of relations
- reload(self)¶
Synchronises with changes in the datasource
- removeExpressionField(self, index: int)¶
Removes an expression field
- Parameters:
index (int) – The index of the field
New in version 2.6.
- removeFeatureRendererGenerator(self, id: str)¶
Removes the feature renderer with matching
id
from the layer.The corresponding generator will be deleted.
See also
See also
New in version 3.18.
- Parameters:
id (str) –
- removeFieldAlias(self, index: int)¶
Removes an alias (a display name) for attributes to display in dialogs
New in version 3.0.
- Parameters:
index (int) –
- 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.
See also
See also
New in version 3.0.
- Parameters:
index (int) –
constraint (QgsFieldConstraints.Constraint) –
- removeJoin(self, joinLayerId: str) bool ¶
Removes a vector layer join
- Return type:
bool
- Returns:
True
if join was found and successfully removed- Parameters:
joinLayerId (str) –
- removeSelection(self)¶
Clear selection
See also
See also
- renameAttribute(self, index: int, newName: str) bool ¶
Renames an attribute field (but does not commit it).
- Parameters:
index (int) – attribute index
newName (str) – new name of field
Note
Calls to
renameAttribute()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.New in version 2.16.
- Return type:
bool
- renderer(self) QgsFeatureRenderer ¶
Returns the feature renderer used for rendering the features in the layer in 2D map views.
See also
- Return type:
- reselect(self)¶
Reselects the previous set of selected features. This is only applicable after a prior call to
removeSelection()
.Any other modifications to the selection following a call to
removeSelection()
clears memory of the previous selection and consequently callingreselect()
has no impact.See also
New in version 3.10.
- resolveReferences(self, project: QgsProject)¶
Resolves references to other layers (kept as layer IDs after reading XML) into layer objects.
New in version 3.0.
- Parameters:
project (QgsProject) –
- rollBack(self, deleteBuffer: bool = True) bool ¶
Stops a current editing operation and discards any uncommitted edits.
If
deleteBuffer
isTrue
the editing buffer will be completely deleted (the default behavior).See also
See also
- Parameters:
deleteBuffer (bool = True) –
- Return type:
bool
- saveStyleToDatabase(self, name: str, description: str, useAsDefault: bool, uiFileContent: str, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) str ¶
Saves named and sld style of the layer to the style table in the db.
- Parameters:
name (str) – Style name
description (str) – A description of the style
useAsDefault (bool) – Set to
True
if style should be used as the default style for the layeruiFileContent (str) –
msgError – will be set to a descriptive error message if any occurs
categories (Union[QgsMapLayer.StyleCategories) – the style categories to be saved.
Note
Prior to QGIS 3.24, this method would show a message box warning when a style with the same
styleName
already existed to confirm replacing the style with the user. Since 3.24, calling this method will ALWAYS overwrite any existing style with the same name. UseQgsProviderRegistry.styleExists()
to test in advance if a style already exists and handle this appropriately in your client code.- Return type:
str
- select(self, featureId: int)¶
Selects feature by its ID
- Parameters:
featureId (int) – The id of the feature to select
See also
select(self, featureIds: object) Selects features by their ID
- Parameters:
featureIds – The ids of the features to select
See also
- selectAll(self)¶
Select all the features
- selectByExpression(self, expression: str, behavior: Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection, context: QgsExpressionContext = None)¶
Selects matching features using an expression.
- Parameters:
expression (str) – expression to evaluate to select features
behavior (Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection) – selection type, allows adding to current selection, removing from selection, etc.
context (
QgsExpressionContext
= None) – since QGIS 3.26, specifies an optional expression context to use when selecting features. If not specified a default one will be built.
See also
See also
New in version 2.16.
- selectByIds(self, ids: object, behavior: Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection)¶
Selects matching features using a list of feature IDs. Will emit the
selectionChanged()
signal with the clearAndSelect flag set.- Parameters:
ids (object) – feature IDs to select
behavior (Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection) – selection type, allows adding to current selection, removing from selection, etc.
See also
See also
New in version 2.16.
- selectByRect(self, rect: QgsRectangle, behavior: Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection)¶
Selects features found within the search rectangle (in layer’s coordinates)
- Parameters:
rect (QgsRectangle) – search rectangle
behavior (Qgis.SelectBehavior = Qgis.SelectBehavior.SetSelection) – selection type, allows adding to current selection, removing from selection, etc.
See also
See also
See also
- selectedFeatureCount(self) int ¶
Returns the number of features that are selected in this layer.
See also
- Return type:
int
- selectedFeatureIds(self) object ¶
Returns a list of the selected features IDs in this layer.
See also
See also
See also
- Return type:
object
- selectedFeatures(self) List[QgsFeature] ¶
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()
orselectedFeatureCount()
if you do not require access to the feature attributes or geometry.- Return type:
List[QgsFeature]
- Returns:
A list of
QgsFeature
See also
See also
- selectionChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- selectionProperties(self) QgsMapLayerSelectionProperties ¶
- Return type:
- sender(self) QObject ¶
- senderSignalIndex(self) int ¶
- setAttributeTableConfig(self, attributeTableConfig: QgsAttributeTableConfig)¶
Sets the attribute table configuration object. This defines the appearance of the attribute table.
- Parameters:
attributeTableConfig (QgsAttributeTableConfig) –
- 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.
- Parameters:
layer (
QgsAuxiliaryLayer
= None) –
- setConstraintExpression(self, index: int, expression: str, description: str = '')¶
Sets 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.
See also
See also
See also
New in version 3.0.
- Parameters:
index (int) –
expression (str) –
description (str = '') –
- setCoordinateSystem(self)¶
Setup the coordinate system transformation for the layer
- setDefaultValueDefinition(self, index: int, definition: QgsDefaultValue)¶
Sets the definition of the expression to use when calculating the default value for a field.
- Parameters:
index (int) – field index
definition (QgsDefaultValue) – default value definition to use and evaluate when calculating default values for field. Pass an empty expression to clear the default.
See also
See also
New in version 3.0.
- setDependencies(self, layers: Iterable[QgsMapLayerDependency]) bool ¶
Sets the list of dependencies.
See also
- Parameters:
layers (Iterable[QgsMapLayerDependency]) – set of
QgsMapLayerDependency
. Only user-defined dependencies will be added- Return type:
bool
- Returns:
False
if a dependency cycle has been detected
New in version 3.0.
- setDiagramLayerSettings(self, s: QgsDiagramLayerSettings)¶
- Parameters:
s (QgsDiagramLayerSettings) –
- setDiagramRenderer(self, r: QgsDiagramRenderer)¶
Sets diagram rendering object (takes ownership)
- Parameters:
r (QgsDiagramRenderer) –
- 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 (str) – The expression which will be used to preview features for this layer
- setEditFormConfig(self, editFormConfig: QgsEditFormConfig)¶
Sets the
editFormConfig
(configuration) of the form used to represent this vector layer.See also
New in version 3.0.
- Parameters:
editFormConfig (QgsEditFormConfig) –
- setEditorWidgetSetup(self, index: int, setup: QgsEditorWidgetSetup)¶
copydoc editorWidgetSetup
- Parameters:
index (int) –
setup (QgsEditorWidgetSetup) –
- setExcludeAttributesWfs(self, att: Iterable[str])¶
A set of attributes that are not advertised in WFS requests with QGIS server.
Deprecated since version QGIS: 3.16 use setFieldConfigurationFlag instead
- Parameters:
att (Iterable[str]) –
- setExcludeAttributesWms(self, att: Iterable[str])¶
A set of attributes that are not advertised in WMS requests with QGIS server.
Deprecated since version QGIS: 3.16 use setFieldConfigurationFlag instead
- Parameters:
att (Iterable[str]) –
- setExtent(self, rect: QgsRectangle)¶
Sets the extent
- Parameters:
rect (QgsRectangle) –
- setFeatureBlendMode(self, blendMode: QPainter.CompositionMode)¶
Sets the blending mode used for rendering each feature
- Parameters:
blendMode (QPainter.CompositionMode) –
- setFieldAlias(self, index: int, aliasString: str)¶
Sets an alias (a display name) for attributes to display in dialogs
New in version 3.0.
- Parameters:
index (int) –
aliasString (str) –
- 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.
See also
See also
New in version 3.0.
- Parameters:
index (int) –
constraint (QgsFieldConstraints.Constraint) –
strength (QgsFieldConstraints.ConstraintStrength = QgsFieldConstraints.ConstraintStrengthHard) –
- setFieldSplitPolicy(self, index: int, policy: Qgis.FieldDomainSplitPolicy)¶
Sets a split
policy
for the field with the specified index.- Raises:
KeyError – if no field with the specified index exists
New in version 3.30.
- Parameters:
index (int) –
policy (Qgis.FieldDomainSplitPolicy) –
- setLabeling(self, labeling: QgsAbstractVectorLayerLabeling)¶
Sets labeling configuration. Takes ownership of the object.
New in version 3.0.
- Parameters:
labeling (QgsAbstractVectorLayerLabeling) –
- setLabelsEnabled(self, enabled: bool)¶
Sets whether labels should be
enabled
for the layer.Note
Labels will only be rendered if
labelsEnabled()
isTrue
and a labeling object is returned bylabeling()
.See also
See also
- Parameters:
enabled (bool) –
- setProviderEncoding(self, encoding: str)¶
Sets the text
encoding
of the data provider.An empty
encoding
string indicates that the provider should automatically select the most appropriate encoding.Warning
Support for setting the provider encoding depends on the underlying data provider. Check
dataProvider()
.capabilities() for theQgsVectorDataProvider
.SelectEncoding capability in order to determine if the provider supports this ability.- Parameters:
encoding (str) –
- setProviderType(self, providerType: str)¶
Sets the
providerType
(provider key)
- 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.
- Parameters:
readExtentFromXml (bool) –
- setReadOnly(self, readonly: bool = True) bool ¶
Makes layer read-only (editing disabled) or not
- Return type:
bool
- Returns:
False
if the layer is in editing yet or if the data source is in read-only mode
See also
- Parameters:
readonly (bool = True) –
- setRenderer(self, r: QgsFeatureRenderer)¶
Sets the feature renderer which will be invoked to represent this layer in 2D map views. Ownership is transferred.
See also
- Parameters:
r (QgsFeatureRenderer) –
- setSimplifyMethod(self, simplifyMethod: QgsVectorSimplifyMethod)¶
Sets the simplification settings for fast rendering of features
New in version 2.2.
- Parameters:
simplifyMethod (QgsVectorSimplifyMethod) –
- setSubsetString(self, subset: str) bool ¶
Sets the string (typically sql) used to define a subset of the layer
- Parameters:
subset (str) – 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.
- Return type:
bool
- Returns:
True
, when setting the subset string was successful,False
otherwise
- setTransformContext(self, transformContext: QgsCoordinateTransformContext)¶
Sets the coordinate transform context to
transformContext
New in version 3.8.
- Parameters:
transformContext (QgsCoordinateTransformContext) –
- setValid(self, valid: bool)¶
Sets whether layer is valid or not
- 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.
- Parameters:
renderContext (QgsRenderContext) –
simplifyHint (QgsVectorSimplifyMethod.SimplifyHint) –
- Return type:
bool
- simplifyMethod(self) QgsVectorSimplifyMethod ¶
Returns the simplification settings for fast rendering of features
New in version 2.2.
- Return type:
- sourceCrs(self) QgsCoordinateReferenceSystem ¶
- Return type:
- sourceExtent(self) QgsRectangle ¶
- Return type:
- sourceName(self) str ¶
- Return type:
str
- splitFeatures(self, splitLine: Iterable[QgsPointXY], topologicalEditing: bool = False) Qgis.GeometryOperationResult ¶
Splits features cut by the given line
- Parameters:
splitLine (Iterable[QgsPointXY]) – line that splits the layer features
topologicalEditing (bool = False) –
True
if topological editing is enabled
- Returns:
Qgis
.GeometryOperationResultSuccess
NothingHappened
LayerNotEditable
InvalidInputGeometryType
InvalidBaseGeometry
GeometryEngineError
SplitCannotSplitPoint
Note
Calls to
splitFeatures()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.splitFeatures(self, splitLine: Iterable[QgsPoint], topologicalEditing: bool = False) -> Qgis.GeometryOperationResult Splits features cut by the given line
- Parameters:
splitLine – line that splits the layer features
topologicalEditing –
True
if topological editing is enabled
- Returns:
Qgis
.GeometryOperationResultSuccess
NothingHappened
LayerNotEditable
InvalidInputGeometryType
InvalidBaseGeometry
GeometryEngineError
SplitCannotSplitPoint
Note
Calls to
splitFeatures()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.splitFeatures(self, curve:
QgsCurve
, preserveCircular: bool = False, topologicalEditing: bool = False) -> Tuple[Qgis.GeometryOperationResult, List[QgsPoint]] Splits features cut by the given curve- Parameters:
curve – curve that splits the layer features
param[out] topologyTestPoints topological points to be tested against other layers :param preserveCircular: whether circular strings are preserved after splitting :param topologicalEditing:
True
if topological editing is enabled- Return type:
- Returns:
Qgis
.GeometryOperationResultSuccess
NothingHappened
LayerNotEditable
InvalidInputGeometryType
InvalidBaseGeometry
GeometryEngineError
SplitCannotSplitPoint
Note
Calls to
splitFeatures()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.New in version 3.16.
- splitParts(self, splitLine: Iterable[QgsPointXY], topologicalEditing: bool = False) Qgis.GeometryOperationResult ¶
Splits parts cut by the given line
- Parameters:
splitLine (Iterable[QgsPointXY]) – line that splits the layer features
topologicalEditing (bool = False) –
True
if topological editing is enabled
- Returns:
Qgis
.GeometryOperationResultSuccess
NothingHappened
LayerNotEditable
InvalidInputGeometryType
InvalidBaseGeometry
GeometryEngineError
SplitCannotSplitPoint
Note
Calls to
splitParts()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.Deprecated since version QGIS: 3.12 - will be removed in QGIS 4.0. Use the variant which accepts
QgsPoint
objects instead ofQgsPointXY
.splitParts(self, splitLine: Iterable[QgsPoint], topologicalEditing: bool = False) -> Qgis.GeometryOperationResult Splits parts cut by the given line
- Parameters:
splitLine – line that splits the layer features
topologicalEditing –
True
if topological editing is enabled
- Return type:
- Returns:
Qgis
.GeometryOperationResultSuccess
NothingHappened
LayerNotEditable
InvalidInputGeometryType
InvalidBaseGeometry
GeometryEngineError
SplitCannotSplitPoint
Note
Calls to
splitParts()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.
- 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 callingrollBack()
.- Return type:
bool
- Returns:
True
if the layer was successfully made editable, orFalse
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
See also
- 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.
- Return type:
str
- storedExpressionManager(self) QgsStoredExpressionManager ¶
Returns the manager of the stored expressions for this layer.
New in version 3.10.
- Return type:
- subsetString(self) str ¶
Returns the string (typically sql) used to define a subset of the layer.
- Return type:
str
- Returns:
The subset string or null QString if not implemented by the provider
- subsetStringChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- supportsEditing(self) bool ¶
Returns whether the layer supports editing or not
- Return type:
bool
- Returns:
False
if the layer is read only or the data provider has no editing capabilities
New in version 3.18.
- supportsEditingChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- symbolFeatureCountMapChanged¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- symbolFeatureIds(self, legendKey: str) object ¶
Ids of features rendered with specified legend key. Features must be first calculated by
countSymbolFeatures()
- Return type:
object
- Returns:
Ids of features rendered by symbol or -1 if failed or Ids are not available
New in version 3.10.
- Parameters:
legendKey (str) –
- temporalProperties(self) QgsMapLayerTemporalProperties ¶
- Return type:
- timerEvent(self, QTimerEvent)¶
- translateFeature(self, featureId: int, dx: float, dy: float) int ¶
Translates feature by dx, dy
- Parameters:
featureId (int) – id of the feature to translate
dx (float) – translation of x-coordinate
dy (float) – translation of y-coordinate
- Return type:
int
- Returns:
0 in case of success
Note
Calls to
translateFeature()
are only valid for layers in which edits have been enabled by a call tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.
- 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 (int) – column index for attribute
substring (str) – substring to match (case insensitive)
limit (int = -1) – maxmum number of the values to return, or -1 to return all unique values
feedback (
QgsFeedback
= None) – optional feedback object for canceling request
- Return type:
List[str]
- 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 (int) – column index for attribute
limit (int = -1) – maximum number of values to return (or -1 if unlimited)
See also
See also
- Return type:
Set[Any]
- updateExpressionField(self, index: int, exp: str)¶
Changes the expression used to define an expression based (virtual) field
- Parameters:
index (int) – The index of the expression to change
exp (str) – 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 (bool = False) –
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 matchingQgsFeature.id()
with the attributes and geometry fromfeature
. Changes are not immediately committed to the layer.If
skipDefaultValue
is set toTrue
, 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 tostartEditing()
. Changes made to features using this method are not committed to the underlying data provider until acommitChanges()
call is made. Any uncommitted changes can be discarded by callingrollBack()
.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 efficientchangeAttributeValue()
orchangeGeometry()
methods instead.See also
See also
See also
See also
- Parameters:
feature (QgsFeature) –
skipDefaultValues (bool = False) –
- Return type:
bool
- 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¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- vectorJoins(self) List[QgsVectorLayerJoinInfo] ¶
- Return type:
List[QgsVectorLayerJoinInfo]
- vectorLayerTypeFlags(self) Qgis.VectorLayerTypeFlags ¶
Returns the vector layer type flags.
See also
New in version 3.24.
- Return type:
- wkbType(self) Qgis.WkbType ¶
Returns the WKBType or WKBUnknown in case of error
- Return type:
- writeCommonStyle(self, layerElement: QDomElement, document: QDomDocument, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories)¶
Write style data common to all layer types
New in version 3.0.
- writeCustomProperties(self, layerNode: QDomNode, doc: QDomDocument)¶
Write custom properties to project file.
- writeCustomSymbology¶
pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL
types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.
- Parameters:
name (str = ...) –
revision (int = ...) –
arguments (Sequence = ...) –
- Return type:
PYQT_SIGNAL
- writeSld(self, node: QDomNode, doc: QDomDocument, errorMessage: str, props: Dict[str, Any] = {}) bool ¶
Writes the symbology of the layer into the document provided in SLD 1.1 format
- Parameters:
node (QDomNode) – the node that will have the style element added to it.
doc (QDomDocument) – the document that will have the QDomNode added.
errorMessage (str) – reference to string that will be updated with any error messages
props (Dict[str) – a open ended set of properties that can drive/inform the SLD encoding
- Return type:
bool
- Returns:
True
in case of success
- writeStyle(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool ¶
- Parameters:
node (QDomNode) –
doc (QDomDocument) –
errorMessage (str) –
context (QgsReadWriteContext) –
categories (Union[QgsMapLayer.StyleCategories) –
- Return type:
bool
- writeStyleManager(self, layerNode: QDomNode, doc: QDomDocument)¶
Write style manager’s configuration (if exists). To be called by subclasses.
- writeSymbology(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool ¶
- Parameters:
node (QDomNode) –
doc (QDomDocument) –
errorMessage (str) –
context (QgsReadWriteContext) –
categories (Union[QgsMapLayer.StyleCategories) –
- Return type:
bool
- writeXml(self, layer_node: QDomNode, doc: QDomDocument, context: QgsReadWriteContext) bool ¶
Writes vector layer specific state to project file Dom node.
Note
Called by
QgsMapLayer.writeXml()
.- Parameters:
layer_node (QDomNode) –
doc (QDomDocument) –
context (QgsReadWriteContext) –
- Return type:
bool