QgsVectorLayer class

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

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

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

Sample usage of the QgsVectorLayer class:

QString uri = "point?crs=epsg:4326&field=id:integer";
QgsVectorLayer *scratchLayer = new 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 (http://www.gdal.org/ogr/ogr_formats.html). The url is the OGR connection string. A wide variety of data formats can be accessed using this driver, including file based formats used by many GIS systems, database formats, and web services. Some of these formats are also supported by custom data providers listed below.

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, starting with QGIS 2.16, a URI constructed using the QgsDataSourceUri class with the following parameters :

  • url=string (mandatory): HTTP url to a WFS server endpoint. e.g http://foobar/wfs
  • typename=string (mandatory): WFS typename
  • srsname=string (recommended): SRS like 'EPSG:XXXX'
  • username=string
  • password=string
  • authcfg=string
  • version=auto/1.0.0/1.1.0/2.0.0 -sql=string: full SELECT SQL statement with optional WHERE, ORDER BY and possibly with JOIN if supported on server
  • filter=string: QGIS expression or OGC/FES filter
  • restrictToRequestBBOX=1: to download only features in the view extent (or more generally in the bounding box of the feature iterator)
  • maxNumFeatures=number
  • IgnoreAxisOrientation=1: to ignore EPSG axis order for WFS 1.1 or 2.0
  • InvertAxisOrientation=1: to invert axis order
  • hideDownloadProgressDialog=1: to hide the download progress dialog

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

Also note:

  • You can use various functions available in the QGIS Expression list, however the function must exist server side and have the same name and arguments to work.
  • Use the special $geometry parameter to provide the layer geometry column as input into the spatial binary operators e.g intersects($geometry, geomFromWKT('POINT (5 6)'))

Delimited text file data provider (delimitedtext)

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

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

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

The url may include the following items:

  • encoding=UTF-8

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

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

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

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

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

  • quote=characters

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

  • escape=characters

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

  • skipLines=n

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

  • useHeader=(yes|no)

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

  • trimFields=(yes|no)

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

  • skipEmptyFields=(yes|no)

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

  • maxFields=#

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

  • decimalPoint=c

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

  • xField=column yField=column

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

  • xyDms=(yes|no)

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

  • wktField=column

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

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

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

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

  • subset=expression

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

  • crs=crsstring

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

-subsetIndex=(yes|no)

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

-spatialIndex=(yes|no)

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

-watchFile=(yes|no)

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

  • quiet

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

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.

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

Base classes

class QgsMapLayer
Base class for all map layer types.
class QgsExpressionContextGenerator
Abstract interface for generating an expression context.
class QgsExpressionContextScopeGenerator
Abstract interface for generating an expression context scope.
class QgsFeatureSink
An interface for objects which accept features via addFeature(s) methods.
class QgsFeatureSource
An interface for objects which provide features via a getFeatures method.

Derived classes

class QgsAuxiliaryLayer
Class allowing to manage the auxiliary storage for a vector layer.

Public types

struct LayerOptions
Setting options for loading vector layers.
enum EditResult { Success = 0, EmptyGeometry = 1, EditFailed = 2, FetchFeatureFailed = 3, InvalidLayer = 4 }
Result of an edit operation.
enum SelectBehavior { SetSelection, AddToSelection, IntersectSelection, RemoveFromSelection }
Selection behavior.
enum VertexMarkerType { SemiTransparentCircle, Cross, NoMarker }
Editing vertex markers.

Public static functions

static void drawVertexMarker(double x, double y, QPainter& p, QgsVectorLayer::VertexMarkerType type, int vertexSize)
Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.)

Constructors, destructors, conversion operators

QgsVectorLayer(const QString& path = QString(), const QString& baseName = QString(), const QString& providerLib = "ogr", const QgsVectorLayer::LayerOptions& options = QgsVectorLayer::LayerOptions()) explicit
Constructor - creates a vector layer.
QgsVectorLayer(const QgsVectorLayer& rhs) deleted
QgsVectorLayer cannot be copied.

Public functions

auto actions() -> QgsActionManager*
Returns all layer actions defined on this layer.
auto actions() const -> const QgsActionManager*
Returns all layer actions defined on this layer.
auto addAttribute(const QgsField& field) -> bool
Add an attribute field (but does not commit it) returns true if the field was added.
auto addExpressionField(const QString& exp, const QgsField& fld) -> int
Add a new field which is calculated by the expression specified.
auto addFeature(QgsFeature& feature, QgsFeatureSink::Flags flags = nullptr) FINAL -> bool virtual
Adds a single feature to the sink.
auto addFeatures(QgsFeatureList& features, QgsFeatureSink::Flags flags = nullptr) FINAL -> bool virtual
Adds a list of features to the sink.
auto addJoin(const QgsVectorLayerJoinInfo& joinInfo) -> bool
Joins another vector layer to this layer.
auto addPart(const QList<QgsPointXY>& ring) -> QgsGeometry::OperationResult
Adds a new part polygon to a multipart feature.
auto addPart(const QgsPointSequence& ring) -> QgsGeometry::OperationResult
Adds a new part polygon to a multipart feature.
auto addPart(QgsCurve* ring) -> QgsGeometry::OperationResult
auto addRing(const QVector<QgsPointXY>& ring, QgsFeatureId* featureId = nullptr) -> QgsGeometry::OperationResult
Adds a ring to polygon/multipolygon features.
auto addRing(QgsCurve* ring, QgsFeatureId* featureId = nullptr) -> QgsGeometry::OperationResult
Adds a ring to polygon/multipolygon features (takes ownership)
auto addTopologicalPoints(const QgsGeometry& geom) -> int
Adds topological points for every vertex of the geometry.
auto addTopologicalPoints(const QgsPointXY& p) -> int
Adds a vertex to segments which intersect point p but don't already have a vertex there.
auto aggregate(QgsAggregateCalculator::Aggregate aggregate, const QString& fieldOrExpression, const QgsAggregateCalculator::AggregateParameters& parameters = QgsAggregateCalculator::AggregateParameters(), QgsExpressionContext* context = nullptr, bool* ok = nullptr) const -> QVariant
Calculates an aggregated value from the layer's features.
auto allowCommit() const -> bool
Controls, if the layer is allowed to commit changes.
auto attributeAlias(int index) const -> QString
Returns the alias of an attribute name or a null string if there is no alias.
auto attributeAliases() const -> QgsStringMap
Returns a map of field name to attribute alias.
auto attributeDisplayName(int index) const -> QString
Convenience function that returns the attribute alias if defined or the field name else.
auto attributeList() const -> QgsAttributeList
Returns list of attribute indexes.
auto attributeTableConfig() const -> QgsAttributeTableConfig
Returns the attribute table configuration object.
auto auxiliaryLayer() -> QgsAuxiliaryLayer*
Returns the current auxiliary layer.
auto auxiliaryLayer() const -> const QgsAuxiliaryLayer*
Returns the current const auxiliary layer.
void beginEditCommand(const QString& text)
Create edit command for undo/redo operations.
auto boundingBoxOfSelected() const -> QgsRectangle
Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned.
auto capabilitiesString() const -> QString
Capabilities for this layer, comma separated and translated.
auto changeAttributeValue(QgsFeatureId fid, int field, const QVariant& newValue, const QVariant& oldValue = QVariant(), bool skipDefaultValues = false) -> bool
Changes an attribute value for a feature (but does not immediately commit the changes).
auto changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap& newValues, const QgsAttributeMap& oldValues = QgsAttributeMap(), bool skipDefaultValues = false) -> bool
Changes attributes' values for a feature (but does not immediately commit the changes).
auto changeGeometry(QgsFeatureId fid, QgsGeometry& geometry, bool skipDefaultValue = false) -> bool
Changes a feature's geometry within the layer's edit buffer (but does not immediately commit the changes).
auto clone() const -> QgsVectorLayer* override
Returns a new instance equivalent to this one.
auto commitChanges() -> bool
Attempts to commit to the underlying data provider any buffered changes made since the last to call to startEditing().
auto commitErrors() const -> QStringList
Returns a list containing any error messages generated when attempting to commit changes to the layer.
auto conditionalStyles() const -> QgsConditionalLayerStyles*
Returns the conditional styles that are set for this layer.
auto constraintDescription(int index) const -> QString
Returns the descriptive name for the constraint expression for a specified field index.
auto constraintExpression(int index) const -> QString
Returns the constraint expression for for a specified field index, if set.
auto countSymbolFeatures() -> QgsVectorLayerFeatureCounter*
Count features for symbols.
auto createExpressionContext() const FINAL -> QgsExpressionContext virtual
This method needs to be reimplemented in all classes which implement this interface and return an expression context.
auto createExpressionContextScope() const FINAL -> QgsExpressionContextScope* virtual
This method needs to be reimplemented in all classes which implement this interface and return an expression context scope.
auto createMapRenderer(QgsRenderContext& rendererContext) FINAL -> QgsMapLayerRenderer* virtual
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
auto dataComment() const -> QString
Returns a description for this layer as defined in the data provider.
auto dataProvider() FINAL -> QgsVectorDataProvider* virtual
Returns the layer's data provider, it may be null.
auto dataProvider() const FINAL -> const QgsVectorDataProvider* virtual
Returns the layer's data provider in a const-correct manner, it may be null.
auto decodedSource(const QString& source, const QString& dataProvider, const QgsReadWriteContext& context) const FINAL -> QString virtual
Called by readLayerXML(), used by derived classes to decode provider's specific data source from project files.
auto defaultValue(int index, const QgsFeature& feature = QgsFeature(), QgsExpressionContext* context = nullptr) const -> QVariant
Returns the calculated default value for the specified field index.
auto defaultValueDefinition(int index) const -> QgsDefaultValue
Returns the definition of the expression used when calculating the default value for a field.
auto deleteAttribute(int attr) -> bool virtual
Deletes an attribute field (but does not commit it).
auto deleteAttributes(const QList<int>& attrs) -> bool
Deletes a list of attribute fields (but does not commit it)
auto deleteFeature(QgsFeatureId fid) -> bool
Deletes a feature from the layer (but does not commit it).
auto deleteFeatures(const QgsFeatureIds& fids) -> bool
Deletes a set of features from the layer (but does not commit it)
auto deleteSelectedFeatures(int* deletedCount = nullptr) -> bool
Deletes the selected features.
auto deleteStyleFromDatabase(const QString& styleId, QString& msgError) -> bool virtual
Delete a style from the database.
auto deleteVertex(QgsFeatureId featureId, int vertex) -> EditResult
Deletes a vertex from a feature.
auto dependencies() const FINAL -> QSet<QgsMapLayerDependency> virtual
Gets the list of dependencies.
void destroyEditCommand()
Destroy active command and reverts all changes in it.
auto diagramsEnabled() const -> bool
Returns whether the layer contains diagrams which are enabled and should be drawn.
auto displayExpression() const -> QString
Returns the preview expression, used to create a human readable preview string.
auto displayField() const -> QString
This is a shorthand for accessing the displayExpression if it is a simple field.
auto editBuffer() -> QgsVectorLayerEditBuffer*
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
auto editBuffer() const -> const QgsVectorLayerEditBuffer*
Buffer with uncommitted editing operations.
auto editFormConfig() const -> QgsEditFormConfig
Returns the configuration of the form used to represent this vector layer.
auto editorWidgetSetup(int index) const -> QgsEditorWidgetSetup
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field at index.
auto encodedSource(const QString& source, const QgsReadWriteContext& context) const FINAL -> QString virtual
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to project files.
void endEditCommand()
Finish edit command and add it to undo/redo stack.
auto excludeAttributesWfs() const -> QSet<QString>
A set of attributes that are not advertised in WFS requests with QGIS server.
auto excludeAttributesWms() const -> QSet<QString>
A set of attributes that are not advertised in WMS requests with QGIS server.
auto expressionField(int index) const -> QString
Returns the expression used for a given expression field.
auto extent() const FINAL -> QgsRectangle virtual
Returns the extent of the layer.
auto featureBlendMode() const -> QPainter::CompositionMode
Returns the current blending mode for features.
auto featureCount(const QString& legendKey) const -> long
Number of features rendered with specified legend key.
auto featureCount() const FINAL -> long virtual
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.
auto fieldConstraints(int fieldIndex) const -> QgsFieldConstraints::Constraints
Returns any constraints which are present for a specified field index.
auto fieldConstraintsAndStrength(int fieldIndex) const -> QMap<QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength>
Returns a map of constraint with their strength for a specific field of the layer.
auto fields() const FINAL -> QgsFields virtual
Returns the list of fields of this layer.
auto geometryOptions() const -> QgsGeometryOptions*
Configuration and logic to apply automatically on any edit happening on this layer.
auto geometryType() const -> QgsWkbTypes::GeometryType
Returns point, line or polygon.
auto getFeature(QgsFeatureId fid) const -> QgsFeature
Query the layer for the feature with the given id.
auto getFeatures(const QgsFeatureRequest& request = QgsFeatureRequest()) const FINAL -> QgsFeatureIterator virtual
Query the layer for features specified in request.
auto getFeatures(const QString& expression) -> QgsFeatureIterator
Query the layer for features matching a given expression.
auto getFeatures(const QgsFeatureIds& fids) -> QgsFeatureIterator
Query the layer for the features with the given ids.
auto getFeatures(const QgsRectangle& rectangle) -> QgsFeatureIterator
Query the layer for the features which intersect the specified rectangle.
auto getGeometry(QgsFeatureId fid) const -> QgsGeometry
Query the layer for the geometry at the given id.
auto getSelectedFeatures(QgsFeatureRequest request = QgsFeatureRequest()) const -> QgsFeatureIterator
Returns an iterator of the selected features.
auto getStyleFromDatabase(const QString& styleId, QString& msgError) -> QString virtual
Will return the named style corresponding to style id provided.
auto hasFeatures() const FINAL -> FeatureAvailability virtual
Determines if this vector layer has features.
auto htmlMetadata() const FINAL -> QString virtual
Obtain a formatted HTML string containing assorted metadata for this layer.
auto insertVertex(double x, double y, QgsFeatureId atFeatureId, int beforeVertex) -> bool
Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature Not meaningful for Point geometries.
auto insertVertex(const QgsPoint& point, QgsFeatureId atFeatureId, int beforeVertex) -> bool
Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0), and feature Not meaningful for Point geometries.
void invertSelection()
Select not selected features and deselect selected ones.
void invertSelectionInRectangle(QgsRectangle& rect)
Invert selection of features found within the search rectangle (in layer's coordinates)
auto isAuxiliaryField(int index, int& srcIndex) const -> bool
Returns true if the field comes from the auxiliary layer, false otherwise.
auto isEditable() const FINAL -> bool virtual
Returns true if the provider is in editing mode.
auto isEditCommandActive() const -> bool
Test if an edit command is active.
auto isModified() const -> bool virtual
Returns true if the provider has been modified since the last commit.
auto isSpatial() const FINAL -> bool virtual
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeometry.
auto joinBuffer() -> QgsVectorLayerJoinBuffer*
Returns the join buffer object.
auto labeling() const -> const QgsAbstractVectorLayerLabeling*
Access to const labeling configuration.
auto labeling() -> QgsAbstractVectorLayerLabeling*
Access to labeling configuration.
auto labelsEnabled() const -> bool
Returns whether the layer contains labels which are enabled and should be drawn.
auto listStylesInDatabase(QStringList& ids, QStringList& names, QStringList& descriptions, QString& msgError) -> int virtual
Lists all the style in db split into related to the layer and not related to.
auto loadAuxiliaryLayer(const QgsAuxiliaryStorage& storage, const QString& key = QString()) -> bool
Loads the auxiliary layer for this vector layer.
auto loadDefaultStyle(bool& resultFlag) FINAL -> QString virtual
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record in the users style table in their personal qgis.db)
auto loadNamedStyle(const QString& theURI, bool& resultFlag, bool loadFromLocalDb, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) -> QString virtual
Load a named style from file/local db/datasource db.
auto loadNamedStyle(const QString& theURI, bool& resultFlag, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) FINAL -> QString virtual
Calls loadNamedStyle( theURI, resultFlag, false ); Retained for backward compatibility.
auto mapTipTemplate() const -> QString
The mapTip is a pretty, html representation for feature information.
auto maximumValue(int index) const FINAL -> QVariant virtual
Returns the maximum value for an attribute column or an invalid variant in case of error.
auto minimumValue(int index) const FINAL -> QVariant virtual
Returns the minimum value for an attribute column or an invalid variant in case of error.
void modifySelection(const QgsFeatureIds& selectIds, const QgsFeatureIds& deselectIds)
Modifies the current selection on this layer.
auto moveVertex(double x, double y, QgsFeatureId atFeatureId, int atVertex) -> bool
Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates.
auto moveVertex(const QgsPoint& p, QgsFeatureId atFeatureId, int atVertex) -> bool
Moves the vertex at the given position number, ring and item (first number is index 0), and feature to the given coordinates.
auto opacity() const -> double
Returns the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).
auto operator=(QgsVectorLayer const& rhs) -> QgsVectorLayer& deleted
QgsVectorLayer cannot be copied.
auto primaryKeyAttributes() const -> QgsAttributeList
Returns the list of attributes which make up the layer's primary keys.
auto readExtentFromXml() const -> 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.
auto readStyle(const QDomNode& node, QString& errorMessage, QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) FINAL -> bool
Read the style for the current layer from the Dom node supplied.
auto readSymbology(const QDomNode& layerNode, QString& errorMessage, QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) FINAL -> bool
Read the symbology for the current layer from the Dom node supplied.
auto readXml(const QDomNode& layer_node, QgsReadWriteContext& context) FINAL -> bool virtual
Reads vector layer specific state from project file Dom node.
auto referencingRelations(int idx) const -> QList<QgsRelation>
Returns the layer's relations, where the foreign key is on this layer.
void reload() FINAL virtual
Synchronises with changes in the datasource.
void removeExpressionField(int index)
Remove an expression field.
void removeFieldAlias(int index)
Removes an alias (a display name) for attributes to display in dialogs.
void removeFieldConstraint(int index, QgsFieldConstraints::Constraint constraint)
Removes a constraint for a specified field index.
auto removeJoin(const QString& joinLayerId) -> bool
Removes a vector layer join.
auto renameAttribute(int index, const QString& newName) -> bool
Renames an attribute field (but does not commit it).
auto renderer() -> QgsFeatureRenderer*
Returns renderer.
auto renderer() const -> const QgsFeatureRenderer*
Returns const renderer.
void resolveReferences(QgsProject* project) FINAL virtual
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
auto rollBack(bool deleteBuffer = true) -> bool
Stops a current editing operation and discards any uncommitted edits.
void saveStyleToDatabase(const QString& name, const QString& description, bool useAsDefault, const QString& uiFileContent, QString& msgError) virtual
Save named and sld style of the layer to the style table in the db.
void selectAll()
Select all the features.
void selectByExpression(const QString& expression, SelectBehavior behavior = SetSelection)
Select matching features using an expression.
void selectByIds(const QgsFeatureIds& ids, SelectBehavior behavior = SetSelection)
Select matching features using a list of feature IDs.
void selectByRect(QgsRectangle& rect, SelectBehavior behavior = SetSelection)
Select features found within the search rectangle (in layer's coordinates)
auto selectedFeatureCount() const -> int
Returns the number of features that are selected in this layer.
auto selectedFeatureIds() const -> const QgsFeatureIds&
Returns a list of the selected features IDs in this layer.
auto selectedFeatures() const -> QgsFeatureList
Returns a copy of the user-selected features.
void setAllowCommit(bool allowCommit)
Controls, if the layer is allowed to commit changes.
void setAttributeTableConfig(const QgsAttributeTableConfig& attributeTableConfig)
Set the attribute table configuration object.
void setAuxiliaryLayer(QgsAuxiliaryLayer* layer = nullptr)
Sets the current auxiliary layer.
void setConstraintExpression(int index, const QString& expression, const QString& description = QString())
Set the constraint expression for the specified field index.
void setCoordinateSystem()
Setup the coordinate system transformation for the layer.
auto setDataSource(const QString& dataSource, const QString& baseName, const QString& provider, bool loadDefaultStyleFlag = false) -> Q_DECL_DEPRECATED void deprecated
Update the data source of the layer.
void setDataSource(const QString& dataSource, const QString& baseName, const QString& provider, const QgsDataProvider::ProviderOptions& options, bool loadDefaultStyleFlag = false) override
Updates the data source of the layer.
void setDefaultValueDefinition(int index, const QgsDefaultValue& definition)
Sets the definition of the expression to use when calculating the default value for a field.
auto setDependencies(const QSet<QgsMapLayerDependency>& layers) FINAL -> bool virtual
Sets the list of dependencies.
void setDiagramRenderer(QgsDiagramRenderer* r)
Sets diagram rendering object (takes ownership)
void setDisplayExpression(const QString& displayExpression)
Set the preview expression, used to create a human readable preview string.
void setEditFormConfig(const QgsEditFormConfig& editFormConfig)
Set the editFormConfig (configuration) of the form used to represent this vector layer.
void setEditorWidgetSetup(int index, const QgsEditorWidgetSetup& setup)
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field at index.
void setExcludeAttributesWfs(const QSet<QString>& att)
A set of attributes that are not advertised in WFS requests with QGIS server.
void setExcludeAttributesWms(const QSet<QString>& att)
A set of attributes that are not advertised in WMS requests with QGIS server.
void setFeatureBlendMode(QPainter::CompositionMode blendMode)
Sets the blending mode used for rendering each feature.
void setFieldAlias(int index, const QString& aliasString)
Sets an alias (a display name) for attributes to display in dialogs.
void setFieldConstraint(int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthHard)
Sets a constraint for a specified field index.
void setLabeling(QgsAbstractVectorLayerLabeling* labeling)
Set labeling configuration.
void setLabelsEnabled(bool enabled)
Sets whether labels should be enabled for the layer.
void setMapTipTemplate(const QString& mapTipTemplate)
The mapTip is a pretty, html representation for feature information.
void setOpacity(double opacity)
Sets the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1.0 (fully opaque).
void setProviderEncoding(const QString& encoding)
Sets the textencoding of the data provider.
void setReadExtentFromXml(bool readExtentFromXml)
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.
auto setReadOnly(bool readonly = true) -> bool
Make layer read-only (editing disabled) or not.
void setRenderer(QgsFeatureRenderer* r)
Set renderer which will be invoked to represent this layer.
void setSimplifyMethod(const QgsVectorSimplifyMethod& simplifyMethod)
Set the simplification settings for fast rendering of features.
auto setSubsetString(const QString& subset) -> bool virtual
Set the string (typically sql) used to define a subset of the layer.
auto simplifyDrawingCanbeApplied(const QgsRenderContext& renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const -> bool
Returns whether the VectorLayer can apply the specified simplification hint.
auto simplifyMethod() const -> const QgsVectorSimplifyMethod&
Returns the simplification settings for fast rendering of features.
auto sourceCrs() const FINAL -> QgsCoordinateReferenceSystem virtual
Returns the coordinate reference system for features in the source.
auto sourceExtent() const FINAL -> QgsRectangle virtual
Returns the extent of all geometries from the source.
auto sourceName() const FINAL -> QString virtual
Returns a friendly display name for the source.
auto splitFeatures(const QVector<QgsPointXY>& splitLine, bool topologicalEditing = false) -> QgsGeometry::OperationResult
Splits features cut by the given line.
auto splitParts(const QVector<QgsPointXY>& splitLine, bool topologicalEditing = false) -> QgsGeometry::OperationResult
Splits parts cut by the given line.
auto storageType() const -> QString
Returns the permanent storage type for this layer as a friendly name.
auto subsetString() const -> QString virtual
Returns the string (typically sql) used to define a subset of the layer.
auto translateFeature(QgsFeatureId featureId, double dx, double dy) -> int
Translates feature by dx, dy.
auto uniqueStringsMatching(int index, const QString& substring, int limit = -1, QgsFeedback* feedback = nullptr) const -> QStringList
Returns unique string values of an attribute which contain a specified subset string.
auto uniqueValues(int fieldIndex, int limit = -1) const FINAL -> QSet<QVariant> virtual
Calculates a list of unique values contained within an attribute in the layer.
void updateExpressionField(int index, const QString& exp)
Changes the expression used to define an expression based (virtual) field.
auto updateFeature(QgsFeature& feature, bool skipDefaultValues = false) -> bool
Updates an existing feature in the layer, replacing the attributes and geometry for the feature with matching QgsFeature::id() with the attributes and geometry from feature.
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider, joined fields and virtual fields.
auto wkbType() const FINAL -> QgsWkbTypes::Type virtual
Returns the WKBType or WKBUnknown in case of error.
auto writeSld(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsStringMap& props = QgsStringMap()) const -> bool
Writes the symbology of the layer into the document provided in SLD 1.1 format.
auto writeStyle(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) const FINAL -> bool
Write just the style information for the layer into the document.
auto writeSymbology(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) const FINAL -> bool
Write the symbology for the layer into the docment provided.
auto writeXml(QDomNode& layer_node, QDomDocument& doc, const QgsReadWriteContext& context) const FINAL -> bool virtual
Write vector layer specific state to project file Dom node.

Signals

void afterRollBack()
Is emitted, after changes are rolled back.
void allowCommitChanged()
Emitted whenever the allowCommitChanged() property of this layer changes.
void attributeAdded(int idx)
Will be emitted, when a new attribute has been added to this vector layer.
void attributeDeleted(int idx)
Will be emitted, when an attribute has been deleted from this vector layer.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant& value)
Is emitted whenever an attribute value change is done in the edit buffer.
void beforeAddingExpressionField(const QString& fieldName)
Will be emitted, when an expression field is going to be added to this vector layer.
void beforeCommitChanges()
Is emitted, before changes are committed to the data provider.
void beforeEditingStarted()
Is emitted, before editing on this layer is started.
void beforeModifiedCheck() const
Is emitted, when layer is checked for modifications. Use for last-minute additions.
void beforeRemovingExpressionField(int idx)
Will be emitted, when an expression field is going to be deleted from this vector layer.
void beforeRollBack()
Is emitted, before changes are rolled back.
void committedAttributesAdded(const QString& layerId, const QList<QgsField>& addedAttributes)
This signal is emitted, when attributes are added to the provider.
void committedAttributesDeleted(const QString& layerId, const QgsAttributeList& deletedAttributes)
This signal is emitted, when attributes are deleted from the provider.
void committedAttributeValuesChanges(const QString& layerId, const QgsChangedAttributesMap& changedAttributesValues)
This signal is emitted, when attribute value changes are saved to the provider.
void committedFeaturesAdded(const QString& layerId, const QgsFeatureList& addedFeatures)
This signal is emitted, when features are added to the provider.
void committedFeaturesRemoved(const QString& layerId, const QgsFeatureIds& deletedFeatureIds)
This signal is emitted, when features are deleted from the provider.
void committedGeometriesChanges(const QString& layerId, const QgsGeometryMap& changedGeometries)
This signal is emitted, when geometry changes are saved to the provider.
void displayExpressionChanged()
Emitted when the display expression changes.
void editCommandDestroyed()
Signal emitted, when an edit command is destroyed.
void editCommandEnded()
Signal emitted, when an edit command successfully ended.
void editCommandStarted(const QString& text)
Signal emitted when a new edit command has been started.
void editFormConfigChanged()
Will be emitted whenever the edit form configuration of this layer changes.
void editingStarted()
Is emitted, when editing on this layer has started.
void editingStopped()
Is emitted, when edited changes successfully have been written to the data provider.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
void featureBlendModeChanged(QPainter::CompositionMode blendMode)
Signal emitted when setFeatureBlendMode() is called.
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
void featuresDeleted(const QgsFeatureIds& fids)
Emitted when features have been deleted.
void geometryChanged(QgsFeatureId fid, const QgsGeometry& geometry)
Is emitted whenever a geometry change is done in the edit buffer.
void labelingFontNotFound(QgsVectorLayer* layer, const QString& fontfamily)
Emitted when the font family defined for labeling layer is not found on system.
void layerModified()
This signal is emitted when modifications has been done on layer.
void mapTipTemplateChanged()
Emitted when the map tip changes.
void opacityChanged(double opacity)
Emitted when the layer's opacity is changed, where opacity is a value between 0 (transparent) and 1 (opaque).
void raiseError(const QString& msg)
Signals an error related to this vector layer.
void readCustomSymbology(const QDomElement& element, QString& errorMessage)
Signal emitted whenever the symbology (QML-file) for this layer is being read.
void readOnlyChanged()
Emitted when the read only state of this layer is changed.
void selectionChanged(const QgsFeatureIds& selected, const QgsFeatureIds& deselected, bool clearAndSelect)
This signal is emitted when selection was changed.
void subsetStringChanged()
Emitted when the layer's subset string has changed.
void symbolFeatureCountMapChanged()
Emitted when the feature count for symbols on this layer has been recalculated.
void updatedFields()
Is emitted, whenever the fields available from this layer have been changed.
void writeCustomSymbology(QDomElement& element, QDomDocument& doc, QString& errorMessage) const
Signal emitted whenever the symbology (QML-file) for this layer is being written.

Public slots

void deselect(QgsFeatureId featureId)
Deselect feature by its ID.
void deselect(const QgsFeatureIds& featureIds)
Deselect features by their ID.
void removeSelection()
Clear selection.
void select(QgsFeatureId featureId)
Select feature by its ID.
void select(const QgsFeatureIds& featureIds)
Select features by their ID.
auto startEditing() -> bool
Makes the layer editable.
void updateExtents(bool force = false) virtual
Update the extents for the layer.

Protected functions

void setExtent(const QgsRectangle& rect) FINAL virtual
Sets the extent.

Private functions

auto isReadOnly() const FINAL -> bool virtual
Returns true if the provider is in read-only mode.

Enum documentation

enum QgsVectorLayer::EditResult

Result of an edit operation.

Enumerators
Success

Edit operation was successful.

EmptyGeometry

Edit operation resulted in an empty geometry.

EditFailed

Edit operation failed.

FetchFeatureFailed

Unable to fetch requested feature.

InvalidLayer

Edit failed due to invalid layer.

enum QgsVectorLayer::SelectBehavior

Selection behavior.

Enumerators
SetSelection

Set selection, removing any existing selection.

AddToSelection

Add selection to current selection.

IntersectSelection

Modify current selection to include only select features which match.

RemoveFromSelection

Remove from current selection.

Function documentation

QgsVectorLayer::QgsVectorLayer(const QString& path = QString(), const QString& baseName = QString(), const QString& providerLib = "ogr", const QgsVectorLayer::LayerOptions& options = QgsVectorLayer::LayerOptions()) explicit

Constructor - creates a vector layer.

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

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.

QgsActionManager* QgsVectorLayer::actions()

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.

const QgsActionManager* QgsVectorLayer::actions() const

Returns all layer actions defined on this layer.

The pointer which is returned is const.

bool QgsVectorLayer::addAttribute(const QgsField& field)

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

int QgsVectorLayer::addExpressionField(const QString& exp, const QgsField& fld)

Add a new field which is calculated by the expression specified.

Parameters
exp The expression which calculates the field
fld The field to calculate
Returns The index of the new field

bool QgsVectorLayer::addFeature(QgsFeature& feature, QgsFeatureSink::Flags flags = nullptr) FINAL virtual

Adds a single feature to the sink.

Returns true in case of success and false in case of failure

Feature addition behavior is controlled by the specified flags.

bool QgsVectorLayer::addFeatures(QgsFeatureList& features, QgsFeatureSink::Flags flags = nullptr) FINAL virtual

Adds a list of features to the sink.

Returns true in case of success and false in case of failure

Feature addition behavior is controlled by the specified flags.

bool QgsVectorLayer::addJoin(const QgsVectorLayerJoinInfo& joinInfo)

Joins another vector layer to this layer.

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

QgsGeometry::OperationResult QgsVectorLayer::addPart(const QList<QgsPointXY>& ring)

Adds a new part polygon to a multipart feature.

Returns

QgsGeometry::OperationResult

  • Success
  • LayerNotEditable
  • SelectionIsEmpty
  • SelectionIsGreaterThanOne
  • AddPartSelectedGeometryNotFound
  • AddPartNotMultiGeometry
  • InvalidBaseGeometry
  • InvalidInputGeometryType

QgsGeometry::OperationResult QgsVectorLayer::addPart(const QgsPointSequence& ring)

Adds a new part polygon to a multipart feature.

Returns

QgsGeometry::OperationResult

  • Success
  • LayerNotEditable
  • SelectionIsEmpty
  • SelectionIsGreaterThanOne
  • AddPartSelectedGeometryNotFound
  • AddPartNotMultiGeometry
  • InvalidBaseGeometry
  • InvalidInputGeometryType

QgsGeometry::OperationResult QgsVectorLayer::addPart(QgsCurve* ring)

QgsGeometry::OperationResult QgsVectorLayer::addRing(const QVector<QgsPointXY>& ring, QgsFeatureId* featureId = nullptr)

Adds a ring to polygon/multipolygon features.

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

QgsGeometry::OperationResult

  • Success
  • LayerNotEditable
  • AddRingNotInExistingFeature
  • InvalidInputGeometryType
  • AddRingNotClosed
  • AddRingNotValid
  • AddRingCrossesExistingRings

QgsGeometry::OperationResult QgsVectorLayer::addRing(QgsCurve* ring, QgsFeatureId* featureId = nullptr)

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

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

QgsGeometry::OperationResult

  • Success
  • LayerNotEditable
  • AddRingNotInExistingFeature
  • InvalidInputGeometryType
  • AddRingNotClosed
  • AddRingNotValid
  • AddRingCrossesExistingRings

int QgsVectorLayer::addTopologicalPoints(const QgsGeometry& geom)

Adds topological points for every vertex of the geometry.

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

int QgsVectorLayer::addTopologicalPoints(const QgsPointXY& p)

Adds a vertex to segments which intersect point p but don't already have a vertex there.

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

If a feature already has a vertex at position p, no additional vertex is inserted. This method is useful for topological editing.

QVariant QgsVectorLayer::aggregate(QgsAggregateCalculator::Aggregate aggregate, const QString& fieldOrExpression, const QgsAggregateCalculator::AggregateParameters& parameters = QgsAggregateCalculator::AggregateParameters(), QgsExpressionContext* context = nullptr, bool* ok = nullptr) const

Calculates an aggregated value from the layer's features.

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

bool QgsVectorLayer::allowCommit() const

Controls, if the layer is allowed to commit changes.

If this is set to false it will not be possible to commit changes on this layer. This can be used to define checks on a layer that need to be pass before the layer can be saved. If you use this API, make sure that:

  • the user is visibly informed that his changes were not saved and what he needs to do in order to be able to save the changes.
  • to set the property back to true, once the user has fixed his data.

When calling

QString QgsVectorLayer::attributeAlias(int index) const

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

QgsAttributeList QgsVectorLayer::attributeList() const

Returns list of attribute indexes.

i.e. a list from 0 ... fieldCount()

QgsAttributeTableConfig QgsVectorLayer::attributeTableConfig() const

Returns the attribute table configuration object.

This defines the appearance of the attribute table.

QgsAuxiliaryLayer* QgsVectorLayer::auxiliaryLayer()

Returns the current auxiliary layer.

const QgsAuxiliaryLayer* QgsVectorLayer::auxiliaryLayer() const

Returns the current const auxiliary layer.

void QgsVectorLayer::beginEditCommand(const QString& text)

Create edit command for undo/redo operations.

Parameters
text text which is to be displayed in undo window

bool QgsVectorLayer::changeAttributeValue(QgsFeatureId fid, int field, const QVariant& newValue, const QVariant& oldValue = QVariant(), bool skipDefaultValues = false)

Changes an attribute value for a feature (but does not immediately commit the changes).

The fid argument specifies the ID of the feature to be changed.

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

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

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

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

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

bool QgsVectorLayer::changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap& newValues, const QgsAttributeMap& oldValues = QgsAttributeMap(), bool skipDefaultValues = false)

Changes attributes' values for a feature (but does not immediately commit the changes).

The fid argument specifies the ID of the feature to be changed.

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

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

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

Returns true if feature's attributes was successfully changed.

bool QgsVectorLayer::changeGeometry(QgsFeatureId fid, QgsGeometry& geometry, bool skipDefaultValue = false)

Changes a feature's geometry within the layer's edit buffer (but does not immediately commit the changes).

The fid argument specifies the ID of the feature to be changed.

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

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

QgsVectorLayer* QgsVectorLayer::clone() const override

Returns a new instance equivalent to this one.

Returns a new layer instance

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

bool QgsVectorLayer::commitChanges()

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.

QStringList QgsVectorLayer::commitErrors() const

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

QgsConditionalLayerStyles* QgsVectorLayer::conditionalStyles() const

Returns the conditional styles that are set for this layer.

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

Style information is used to render conditional formatting in the attribute table.

QString QgsVectorLayer::constraintDescription(int index) const

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

QString QgsVectorLayer::constraintExpression(int index) const

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

QgsVectorLayerFeatureCounter* QgsVectorLayer::countSymbolFeatures()

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.

QgsExpressionContext QgsVectorLayer::createExpressionContext() const FINAL virtual

This method needs to be reimplemented in all classes which implement this interface and return an expression context.

QgsExpressionContextScope* QgsVectorLayer::createExpressionContextScope() const FINAL virtual

This method needs to be reimplemented in all classes which implement this interface and return an expression context scope.

QgsMapLayerRenderer* QgsVectorLayer::createMapRenderer(QgsRenderContext& rendererContext) FINAL virtual

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

const QgsVectorDataProvider* QgsVectorLayer::dataProvider() const FINAL virtual

Returns the layer's data provider in a const-correct manner, it may be null.

QString QgsVectorLayer::decodedSource(const QString& source, const QString& dataProvider, const QgsReadWriteContext& context) const FINAL virtual

Called by readLayerXML(), used by derived classes to decode provider's specific data source from project files.

Parameters
source data source to decode, typically read from layer's DOM element "datasource"
dataProvider string identification of data provider (e.g. "ogr"), typically read from layer's DOM element
context reading context (e.g. for conversion between relative and absolute paths)
Returns decoded source, typically to be used as the layer's datasource

Typically resolving absolute or relative paths, usernames and passwords or drivers prefixes ("HDF5:")

QVariant QgsVectorLayer::defaultValue(int index, const QgsFeature& feature = QgsFeature(), QgsExpressionContext* context = nullptr) const

Returns the calculated default value for the specified field index.

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

The default value may be taken from a client side default value expression (see setDefaultValueDefinition()) or taken from the underlying data provider.

QgsDefaultValue QgsVectorLayer::defaultValueDefinition(int index) const

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

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

bool QgsVectorLayer::deleteAttribute(int attr) virtual

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

bool QgsVectorLayer::deleteAttributes(const QList<int>& attrs)

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

Parameters
attrs the indices of the attributes to delete
Returns true if at least one attribute has been deleted

bool QgsVectorLayer::deleteFeature(QgsFeatureId fid)

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

bool QgsVectorLayer::deleteFeatures(const QgsFeatureIds& fids)

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

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

bool QgsVectorLayer::deleteSelectedFeatures(int* deletedCount = nullptr)

Deletes the selected features.

Returns true in case of success and false otherwise

bool QgsVectorLayer::deleteStyleFromDatabase(const QString& styleId, QString& msgError) virtual

Delete a style from the database.

Parameters
styleId the provider's layer_styles table id of the style to delete
msgError reference to string that will be updated with any error messages
Returns true in case of success

EditResult QgsVectorLayer::deleteVertex(QgsFeatureId featureId, int vertex)

Deletes a vertex from a feature.

Parameters
featureId ID of feature to remove vertex from
vertex index of vertex to delete

QSet<QgsMapLayerDependency> QgsVectorLayer::dependencies() const FINAL virtual

Gets the list of dependencies.

Returns a set of QgsMapLayerDependency

This includes data dependencies set by the user (

bool QgsVectorLayer::diagramsEnabled() const

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

Returns true if layer contains enabled diagrams

QString QgsVectorLayer::displayExpression() const

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

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

Uses QgsExpression

QString QgsVectorLayer::displayField() const

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.

const QgsVectorLayerEditBuffer* QgsVectorLayer::editBuffer() const

Buffer with uncommitted editing operations.

Only valid after editing has been turned on.

QgsEditFormConfig QgsVectorLayer::editFormConfig() const

Returns the configuration of the form used to represent this vector layer.

Returns The configuration of this layers' form

QgsEditorWidgetSetup QgsVectorLayer::editorWidgetSetup(int index) const

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

QString QgsVectorLayer::encodedSource(const QString& source, const QgsReadWriteContext& context) const FINAL virtual

Called by writeLayerXML(), used by derived classes to encode provider's specific data source to project files.

Parameters
source data source to encode, typically QgsMapLayer::source()
context writing context (e.g. for conversion between relative and absolute paths)
Returns encoded source, typically to be written in the DOM element "datasource"

Typically resolving absolute or relative paths, usernames and passwords or drivers prefixes ("HDF5:")

QString QgsVectorLayer::expressionField(int index) const

Returns the expression used for a given expression field.

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

long QgsVectorLayer::featureCount(const QString& legendKey) const

Number of features rendered with specified legend key.

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

Features must be first calculated by countSymbolFeatures()

QgsFieldConstraints::Constraints QgsVectorLayer::fieldConstraints(int fieldIndex) const

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.

QMap<QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength> QgsVectorLayer::fieldConstraintsAndStrength(int fieldIndex) const

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

Parameters
fieldIndex field index

QgsFields QgsVectorLayer::fields() const FINAL virtual

Returns the list of fields of this layer.

Returns A list of fields

This also includes fields which have not yet been saved to the provider.

QgsGeometryOptions* QgsVectorLayer::geometryOptions() const

Configuration and logic to apply automatically on any edit happening on this layer.

QgsFeature QgsVectorLayer::getFeature(QgsFeatureId fid) const

Query the layer for the feature with the given id.

If there is no such feature, the returned feature will be invalid.

QgsFeatureIterator QgsVectorLayer::getFeatures(const QgsFeatureRequest& request = QgsFeatureRequest()) const FINAL virtual

Query the layer for features specified in request.

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

QgsGeometry QgsVectorLayer::getGeometry(QgsFeatureId fid) const

Query the layer for the geometry at the given id.

If there is no such feature, the returned geometry will be invalid.

QgsFeatureIterator QgsVectorLayer::getSelectedFeatures(QgsFeatureRequest request = QgsFeatureRequest()) const

Returns an iterator of the selected features.

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

FeatureAvailability QgsVectorLayer::hasFeatures() const FINAL virtual

Determines if this vector layer has features.

QString QgsVectorLayer::htmlMetadata() const FINAL virtual

Obtain a formatted HTML string containing assorted metadata for this layer.

bool QgsVectorLayer::insertVertex(double x, double y, QgsFeatureId atFeatureId, int beforeVertex)

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

bool QgsVectorLayer::insertVertex(const QgsPoint& point, QgsFeatureId atFeatureId, int beforeVertex)

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

void QgsVectorLayer::invertSelectionInRectangle(QgsRectangle& rect)

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

Parameters
rect The rectangle in which the selection of features will be inverted

bool QgsVectorLayer::isAuxiliaryField(int index, int& srcIndex) const

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

bool QgsVectorLayer::isEditCommandActive() const

Test if an edit command is active.

QgsVectorLayerJoinBuffer* QgsVectorLayer::joinBuffer()

Returns the join buffer object.

const QgsAbstractVectorLayerLabeling* QgsVectorLayer::labeling() const

Access to const labeling configuration.

May be null if labeling is not used.

QgsAbstractVectorLayerLabeling* QgsVectorLayer::labeling()

Access to labeling configuration.

May be null if labeling is not used.

bool QgsVectorLayer::labelsEnabled() const

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

Returns true if layer contains enabled labels

int QgsVectorLayer::listStylesInDatabase(QStringList& ids, QStringList& names, QStringList& descriptions, QString& msgError) virtual

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

Parameters
ids the list in which will be stored the style db ids
names the list in which will be stored the style names
descriptions the list in which will be stored the style descriptions
msgError
Returns the number of styles related to current layer

bool QgsVectorLayer::loadAuxiliaryLayer(const QgsAuxiliaryStorage& storage, const QString& key = QString())

Loads the auxiliary layer for this vector layer.

Parameters
storage The auxiliary storage where to look for the table
key The key to use for joining.
Returns true if the auxiliary layer is well loaded, false otherwise

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.

QString QgsVectorLayer::loadDefaultStyle(bool& resultFlag) FINAL virtual

Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record in the users style table in their personal qgis.db)

Parameters
resultFlag a reference to a flag that will be set to false if we did not manage to load the default style.
Returns a QString with any status messages

QString QgsVectorLayer::loadNamedStyle(const QString& theURI, bool& resultFlag, bool loadFromLocalDb, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) virtual

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

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

QString QgsVectorLayer::mapTipTemplate() const

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

It may also contain embedded expressions.

QVariant QgsVectorLayer::maximumValue(int index) const FINAL virtual

Returns the maximum value for an attribute column or an invalid variant in case of error.

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

QVariant QgsVectorLayer::minimumValue(int index) const FINAL virtual

Returns the minimum value for an attribute column or an invalid variant in case of error.

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

void QgsVectorLayer::modifySelection(const QgsFeatureIds& selectIds, const QgsFeatureIds& deselectIds)

Modifies the current selection on this layer.

Parameters
selectIds Select these ids
deselectIds Deselect these ids

bool QgsVectorLayer::moveVertex(double x, double y, QgsFeatureId atFeatureId, int atVertex)

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

bool QgsVectorLayer::moveVertex(const QgsPoint& p, QgsFeatureId atFeatureId, int atVertex)

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

double QgsVectorLayer::opacity() const

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

bool QgsVectorLayer::readExtentFromXml() const

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.

bool QgsVectorLayer::readStyle(const QDomNode& node, QString& errorMessage, QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) FINAL

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

Parameters
node node that will contain the style definition for this layer.
errorMessage reference to string that will be updated with any error messages
context reading context (used for transform from relative to absolute paths)
categories the style categories to be read
Returns true in case of success.

bool QgsVectorLayer::readSymbology(const QDomNode& layerNode, QString& errorMessage, QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) FINAL

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

Parameters
layerNode node that will contain the symbology definition for this layer.
errorMessage reference to string that will be updated with any error messages
context reading context (used for transform from relative to absolute paths)
categories the style categories to be read
Returns true in case of success.

bool QgsVectorLayer::readXml(const QDomNode& layer_node, QgsReadWriteContext& context) FINAL virtual

Reads vector layer specific state from project file Dom node.

QList<QgsRelation> QgsVectorLayer::referencingRelations(int idx) const

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

Parameters
idx Only get relations, where idx forms part of the foreign key
Returns A list of relations

void QgsVectorLayer::removeExpressionField(int index)

Remove an expression field.

Parameters
index The index of the field

void QgsVectorLayer::removeFieldAlias(int index)

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

void QgsVectorLayer::removeFieldConstraint(int index, QgsFieldConstraints::Constraint 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.

bool QgsVectorLayer::removeJoin(const QString& joinLayerId)

Removes a vector layer join.

Returns true if join was found and successfully removed

bool QgsVectorLayer::renameAttribute(int index, const QString& newName)

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

Parameters
index attribute index
newName new name of field

const QgsFeatureRenderer* QgsVectorLayer::renderer() const

Returns const renderer.

void QgsVectorLayer::resolveReferences(QgsProject* project) FINAL virtual

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

bool QgsVectorLayer::rollBack(bool deleteBuffer = true)

Stops a current editing operation and discards any uncommitted edits.

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

void QgsVectorLayer::saveStyleToDatabase(const QString& name, const QString& description, bool useAsDefault, const QString& uiFileContent, QString& msgError) virtual

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

Parameters
name
description
useAsDefault
uiFileContent
msgError

void QgsVectorLayer::selectByExpression(const QString& expression, SelectBehavior behavior = SetSelection)

Select matching features using an expression.

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

void QgsVectorLayer::selectByIds(const QgsFeatureIds& ids, SelectBehavior behavior = SetSelection)

Select matching features using a list of feature IDs.

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

Will emit the selectionChanged() signal with the clearAndSelect flag set.

void QgsVectorLayer::selectByRect(QgsRectangle& rect, SelectBehavior behavior = SetSelection)

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

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

int QgsVectorLayer::selectedFeatureCount() const

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

const QgsFeatureIds& QgsVectorLayer::selectedFeatureIds() const

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

QgsFeatureList QgsVectorLayer::selectedFeatures() const

Returns a copy of the user-selected features.

Returns A list of QgsFeature

void QgsVectorLayer::setAllowCommit(bool allowCommit)

Controls, if the layer is allowed to commit changes.

If this is set to false it will not be possible to commit changes on this layer. This can be used to define checks on a layer that need to be pass before the layer can be saved. If you use this API, make sure that:

  • the user is visibly informed that his changes were not saved and what he needs to do in order to be able to save the changes.
  • to set the property back to true, once the user has fixed his data.

When calling

void QgsVectorLayer::setAttributeTableConfig(const QgsAttributeTableConfig& attributeTableConfig)

Set the attribute table configuration object.

This defines the appearance of the attribute table.

void QgsVectorLayer::setAuxiliaryLayer(QgsAuxiliaryLayer* layer = nullptr)

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.

void QgsVectorLayer::setConstraintExpression(int index, const QString& expression, const QString& description = QString())

Set the constraint expression for the specified field index.

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

Q_DECL_DEPRECATED void QgsVectorLayer::setDataSource(const QString& dataSource, const QString& baseName, const QString& provider, bool loadDefaultStyleFlag = false)

Update the data source of the layer.

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

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

void QgsVectorLayer::setDataSource(const QString& dataSource, const QString& baseName, const QString& provider, const QgsDataProvider::ProviderOptions& options, bool loadDefaultStyleFlag = false) override

Updates the data source of the layer.

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

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

void QgsVectorLayer::setDefaultValueDefinition(int index, const QgsDefaultValue& definition)

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

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

bool QgsVectorLayer::setDependencies(const QSet<QgsMapLayerDependency>& layers) FINAL virtual

Sets the list of dependencies.

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

void QgsVectorLayer::setDisplayExpression(const QString& displayExpression)

Set the preview expression, used to create a human readable preview string.

Parameters
displayExpression The expression which will be used to preview features for this layer

Used e.g. in the attribute table feature list. Uses QgsExpression.

void QgsVectorLayer::setEditFormConfig(const QgsEditFormConfig& editFormConfig)

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

void QgsVectorLayer::setEditorWidgetSetup(int index, const QgsEditorWidgetSetup& setup)

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

void QgsVectorLayer::setFieldAlias(int index, const QString& aliasString)

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

void QgsVectorLayer::setFieldConstraint(int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength = 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.

void QgsVectorLayer::setLabeling(QgsAbstractVectorLayerLabeling* labeling)

Set labeling configuration.

Takes ownership of the object.

void QgsVectorLayer::setLabelsEnabled(bool enabled)

Sets whether labels should be enabled for the layer.

void QgsVectorLayer::setMapTipTemplate(const QString& mapTipTemplate)

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

It may also contain embedded expressions.

void QgsVectorLayer::setOpacity(double opacity)

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

void QgsVectorLayer::setReadExtentFromXml(bool readExtentFromXml)

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.

bool QgsVectorLayer::setReadOnly(bool readonly = true)

Make layer read-only (editing disabled) or not.

Returns false if the layer is in editing yet

void QgsVectorLayer::setRenderer(QgsFeatureRenderer* r)

Set renderer which will be invoked to represent this layer.

Ownership is transferred.

void QgsVectorLayer::setSimplifyMethod(const QgsVectorSimplifyMethod& simplifyMethod)

Set the simplification settings for fast rendering of features.

bool QgsVectorLayer::setSubsetString(const QString& subset) virtual

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

Parameters
subset The subset string. This may be the where clause of a sql statement or other definition string specific to the underlying dataprovider and data store.
Returns true, when setting the subset string was successful, false otherwise

bool QgsVectorLayer::simplifyDrawingCanbeApplied(const QgsRenderContext& renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const

Returns whether the VectorLayer can apply the specified simplification hint.

const QgsVectorSimplifyMethod& QgsVectorLayer::simplifyMethod() const

Returns the simplification settings for fast rendering of features.

QgsRectangle QgsVectorLayer::sourceExtent() const FINAL virtual

Returns the extent of all geometries from the source.

The base class implementation uses a non-optimised approach of looping through all features in the source.

QString QgsVectorLayer::sourceName() const FINAL virtual

Returns a friendly display name for the source.

The returned value can be an empty string.

QgsGeometry::OperationResult QgsVectorLayer::splitFeatures(const QVector<QgsPointXY>& splitLine, bool topologicalEditing = false)

Splits features cut by the given line.

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

QgsGeometry::OperationResult

  • Success
  • NothingHappened
  • LayerNotEditable
  • InvalidInputGeometryType
  • InvalidBaseGeometry
  • GeometryEngineError
  • SplitCannotSplitPoint

QgsGeometry::OperationResult QgsVectorLayer::splitParts(const QVector<QgsPointXY>& splitLine, bool topologicalEditing = false)

Splits parts cut by the given line.

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

QgsGeometry::OperationResult

  • Success
  • NothingHappened
  • LayerNotEditable
  • InvalidInputGeometryType
  • InvalidBaseGeometry
  • GeometryEngineError
  • SplitCannotSplitPoint

QString QgsVectorLayer::storageType() const

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.

QString QgsVectorLayer::subsetString() const virtual

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

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

int QgsVectorLayer::translateFeature(QgsFeatureId featureId, double dx, double dy)

Translates feature by dx, dy.

Parameters
featureId id of the feature to translate
dx translation of x-coordinate
dy translation of y-coordinate
Returns 0 in case of success

QStringList QgsVectorLayer::uniqueStringsMatching(int index, const QString& substring, int limit = -1, QgsFeedback* feedback = nullptr) const

Returns unique string values of an attribute which contain a specified subset string.

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

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

QSet<QVariant> QgsVectorLayer::uniqueValues(int fieldIndex, int limit = -1) const FINAL virtual

Calculates a list of unique values contained within an attribute in the layer.

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

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

void QgsVectorLayer::updateExpressionField(int index, const QString& exp)

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

Parameters
index The index of the expression to change
exp The new expression to set

bool QgsVectorLayer::updateFeature(QgsFeature& feature, bool skipDefaultValues = false)

Updates an existing feature in the layer, replacing the attributes and geometry for the feature with matching QgsFeature::id() with the attributes and geometry from feature.

Changes are not immediately committed to the layer.

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

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

void QgsVectorLayer::updateFields()

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.

bool QgsVectorLayer::writeSld(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsStringMap& props = QgsStringMap()) const

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

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

bool QgsVectorLayer::writeStyle(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) const FINAL

Write just the style information for the layer into the document.

Parameters
node the node that will have the style element added to it.
doc the document that will have the QDomNode added.
errorMessage reference to string that will be updated with any error messages
context writing context (used for transform from absolute to relative paths)
categories the style categories to be written
Returns true in case of success.

bool QgsVectorLayer::writeSymbology(QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsReadWriteContext& context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories) const FINAL

Write the symbology for the layer into the docment provided.

Parameters
node the node that will have the style element added to it.
doc the document that will have the QDomNode added.
errorMessage reference to string that will be updated with any error messages
context writing context (used for transform from absolute to relative paths)
categories the style categories to be written
Returns true in case of success.

bool QgsVectorLayer::writeXml(QDomNode& layer_node, QDomDocument& doc, const QgsReadWriteContext& context) const FINAL virtual

Write vector layer specific state to project file Dom node.

void QgsVectorLayer::afterRollBack() signal

Is emitted, after changes are rolled back.

void QgsVectorLayer::allowCommitChanged() signal

Emitted whenever the allowCommitChanged() property of this layer changes.

void QgsVectorLayer::attributeAdded(int idx) signal

Will be emitted, when a new attribute has been added to this vector layer.

Parameters
idx The index of the new attribute

Applies only to types QgsFields::OriginEdit, QgsFields::OriginProvider and QgsFields::OriginExpression

void QgsVectorLayer::attributeDeleted(int idx) signal

Will be emitted, when an attribute has been deleted from this vector layer.

Parameters
idx The index of the deleted attribute

Applies only to types QgsFields::OriginEdit, QgsFields::OriginProvider and QgsFields::OriginExpression

void QgsVectorLayer::attributeValueChanged(QgsFeatureId fid, int idx, const QVariant& value) signal

Is emitted whenever an attribute value change is done in the edit buffer.

Parameters
fid The id of the changed feature
idx The attribute index of the changed attribute
value The new value of the attribute

Note that at this point the attribute change is not yet saved to the provider.

void QgsVectorLayer::beforeAddingExpressionField(const QString& fieldName) signal

Will be emitted, when an expression field is going to be added to this vector layer.

Parameters
fieldName The name of the attribute to be added

Applies only to types QgsFields::OriginExpression

void QgsVectorLayer::beforeRemovingExpressionField(int idx) signal

Will be emitted, when an expression field is going to be deleted from this vector layer.

Parameters
idx The index of the attribute to be deleted

Applies only to types QgsFields::OriginExpression

void QgsVectorLayer::displayExpressionChanged() signal

Emitted when the display expression changes.

void QgsVectorLayer::editCommandDestroyed() signal

Signal emitted, when an edit command is destroyed.

void QgsVectorLayer::editCommandEnded() signal

Signal emitted, when an edit command successfully ended.

void QgsVectorLayer::editCommandStarted(const QString& text) signal

Signal emitted when a new edit command has been started.

Parameters
text Description for this edit command

void QgsVectorLayer::editFormConfigChanged() signal

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

void QgsVectorLayer::featureAdded(QgsFeatureId fid) signal

Emitted when a new feature has been added to the layer.

Parameters
fid The id of the new feature

void QgsVectorLayer::featureDeleted(QgsFeatureId fid) signal

Emitted when a feature has been deleted.

Parameters
fid The id of the feature which has been deleted

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

void QgsVectorLayer::featuresDeleted(const QgsFeatureIds& fids) signal

Emitted when features have been deleted.

Parameters
fids The feature ids that have been deleted.

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

void QgsVectorLayer::geometryChanged(QgsFeatureId fid, const QgsGeometry& geometry) signal

Is emitted whenever a geometry change is done in the edit buffer.

Parameters
fid The id of the changed feature
geometry The new geometry

Note that at this point the geometry change is not yet saved to the provider.

void QgsVectorLayer::mapTipTemplateChanged() signal

Emitted when the map tip changes.

void QgsVectorLayer::opacityChanged(double opacity) signal

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

void QgsVectorLayer::readCustomSymbology(const QDomElement& element, QString& errorMessage) signal

Signal emitted whenever the symbology (QML-file) for this layer is being read.

Parameters
element The XML layer style element.
errorMessage Write error messages into this string.

If there is custom style information saved in the file, you can connect to this signal and update the layer style accordingly.

void QgsVectorLayer::readOnlyChanged() signal

Emitted when the read only state of this layer is changed.

Only applies to manually set readonly state, not to the edit mode.

void QgsVectorLayer::selectionChanged(const QgsFeatureIds& selected, const QgsFeatureIds& deselected, bool clearAndSelect) signal

This signal is emitted when selection was changed.

Parameters
selected Newly selected feature ids
deselected Ids of all features which have previously been selected but are not any more
clearAndSelect In case this is set to true, the old selection was dismissed and the new selection corresponds to selected

void QgsVectorLayer::subsetStringChanged() signal

Emitted when the layer's subset string has changed.

void QgsVectorLayer::symbolFeatureCountMapChanged() signal

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

void QgsVectorLayer::updatedFields() signal

Is emitted, whenever the fields available from this layer have been changed.

This can be due to manually adding attributes or due to a join.

void QgsVectorLayer::writeCustomSymbology(QDomElement& element, QDomDocument& doc, QString& errorMessage) const signal

Signal emitted whenever the symbology (QML-file) for this layer is being written.

Parameters
element The XML element where you can add additional style information to.
doc The XML document that you can use to create new XML nodes.
errorMessage Write error messages into this string.

If there is custom style information you want to save to the file, you can connect to this signal and update the element accordingly.

void QgsVectorLayer::deselect(QgsFeatureId featureId) public slot

Deselect feature by its ID.

Parameters
featureId The id of the feature to deselect

void QgsVectorLayer::deselect(const QgsFeatureIds& featureIds) public slot

Deselect features by their ID.

Parameters
featureIds The ids of the features to deselect

void QgsVectorLayer::removeSelection() public slot

Clear selection.

void QgsVectorLayer::select(QgsFeatureId featureId) public slot

Select feature by its ID.

Parameters
featureId The id of the feature to select

void QgsVectorLayer::select(const QgsFeatureIds& featureIds) public slot

Select features by their ID.

Parameters
featureIds The ids of the features to select

bool QgsVectorLayer::startEditing() public slot

Makes the layer editable.

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

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

void QgsVectorLayer::updateExtents(bool force = false) virtual public slot

Update the extents for the layer.

Parameters
force true to update layer extent even if it's read from xml by default, false otherwise

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