Class: QgsVectorLayerUtils

class qgis.core.QgsVectorLayerUtils

Bases: sip.wrapper

Contains utility methods for working with QgsVectorLayers.

Methods

attributeHasConstraints

Returns True if a feature attribute has active constraints.

createFeature

Creates a new feature ready for insertion into a layer.

createFeatures

Creates a set of new features ready for insertion into a layer.

createUniqueValue

Returns a new attribute value for the specified field index which is guaranteed to be unique.

createUniqueValueFromCache

Returns a new attribute value for the specified field index which is guaranteed to be unique within regard to existingValues.

duplicateFeature

Duplicates a feature and it's children (one level deep).

fieldEditabilityDependsOnFeature

Returns True if the editability of the field at index fieldIndex from layer may vary feature by feature.

fieldIsEditable

Tests whether a field is editable for a particular feature.

fieldIsReadOnly

rtype:

bool

getDoubleValues

Fetches all double values from a specified field name or expression.

getFeatureDisplayString

rtype:

str

getValues

Fetches all values from a specified field name or expression.

getValuesIterator

Create a feature iterator for a specified field name or expression.

guessFriendlyIdentifierField

Given a set of fields, attempts to pick the "most useful" field for user-friendly identification of features.

guessFriendlyIdentifierFieldV2

Given a set of fields, attempts to pick the "most useful" field for user-friendly identification of features.

impactsCascadeFeatures

return:

True if at least one feature of the fids on layer is connected as parent in at

makeFeatureCompatible

Converts input feature to be compatible with the given layer.

makeFeaturesCompatible

Converts input features to be compatible with the given layer.

matchAttributesToFields

Matches the attributes in feature to the specified fields.

validateAttribute

Tests a feature attribute value to check whether it passes all constraints which are present on the corresponding field.

valueExists

Returns True if the specified value already exists within a field.

Attributes

IgnoreAuxiliaryLayers

class CascadedFeatureFlag

Bases: int

class CascadedFeatureFlags
class CascadedFeatureFlags(f: QgsVectorLayerUtils.CascadedFeatureFlags | QgsVectorLayerUtils.CascadedFeatureFlag)
class CascadedFeatureFlags(a0: QgsVectorLayerUtils.CascadedFeatureFlags)

Bases: sip.wrapper

IgnoreAuxiliaryLayers = 2
class QgsDuplicateFeatureContext

Bases: sip.wrapper

Contains mainly the QMap with QgsVectorLayer and QgsFeatureIds do list all the duplicated features

QgsVectorLayerUtils.QgsDuplicateFeatureContext() Constructor for QgsDuplicateFeatureContext

QgsVectorLayerUtils.QgsDuplicateFeatureContext(a0: QgsVectorLayerUtils.:py:class:.QgsDuplicateFeatureContext)

duplicatedFeatures(self, layer: QgsVectorLayer | None) Any

Returns the duplicated features in the given layer

Parameters:

layer (Optional[QgsVectorLayer])

Return type:

Any

layers(self) List[QgsVectorLayer]

Returns all the layers on which features have been duplicated

Return type:

List[QgsVectorLayer]

class QgsFeatureData

Bases: sip.wrapper

Encapsulate geometry and attributes for new features, to be passed to createFeatures

See also

createFeatures()

Added in version 3.6.

QgsVectorLayerUtils.QgsFeatureData(geometry: QgsGeometry = QgsGeometry(), attributes: Dict[int, Any] = {}) Constructs a new QgsFeatureData with given geometry and attributes

QgsVectorLayerUtils.QgsFeatureData(a0: QgsVectorLayerUtils.:py:class:.QgsFeatureData)

attributes(self) Dict[int, Any]

Returns attributes

Return type:

Dict[int, Any]

geometry(self) QgsGeometry

Returns geometry

Return type:

QgsGeometry

attributeHasConstraints(layer: QgsVectorLayer | None, attributeIndex: int) bool

Returns True if a feature attribute has active constraints.

Parameters:
  • layer (Optional[QgsVectorLayer]) – the vector layer from which field constraints will be checked for

  • attributeIndex (int) – the attribute index

Added in version 3.30.

Return type:

bool

createFeature(layer: QgsVectorLayer | None, geometry: QgsGeometry = QgsGeometry(), attributes: Dict[int, Any] = {}, context: QgsExpressionContext | None = None) QgsFeature

Creates a new feature ready for insertion into a layer. Default values and constraints (e.g., unique constraints) will automatically be handled. An optional attribute map can be passed for the new feature to copy as many attribute values as possible from the map, assuming that they respect the layer’s constraints. Note that the created feature is not automatically inserted into the layer.

See also

createFeatures()

Parameters:
Return type:

QgsFeature

createFeatures(layer: QgsVectorLayer | None, featuresData: Iterable[QgsVectorLayerUtils.QgsFeatureData], context: QgsExpressionContext | None = None) List[QgsFeature]

Creates a set of new features ready for insertion into a layer. Default values and constraints (e.g., unique constraints) will automatically be handled. Note that the created features are not automatically inserted into the layer.

See also

createFeature()

Added in version 3.6.

Parameters:
Return type:

List[QgsFeature]

createUniqueValue(layer: QgsVectorLayer | None, fieldIndex: int, seed: Any = None) Any

Returns a new attribute value for the specified field index which is guaranteed to be unique. The optional seed value can be used as a basis for generated values.

See also

valueExists()

Parameters:
Return type:

Any

createUniqueValueFromCache(layer: QgsVectorLayer | None, fieldIndex: int, existingValues: Iterable[Any], seed: Any = None) Any

Returns a new attribute value for the specified field index which is guaranteed to be unique within regard to existingValues. The optional seed value can be used as a basis for generated values.

Added in version 3.6.

Parameters:
  • layer (Optional[QgsVectorLayer])

  • fieldIndex (int)

  • existingValues (Iterable[Any])

  • seed (Any = None)

Return type:

Any

duplicateFeature(layer: QgsVectorLayer | None, feature: QgsFeature, project: QgsProject | None, maxDepth: int = 0)

Duplicates a feature and it’s children (one level deep). It calls CreateFeature, so default values and constraints (e.g., unique constraints) will automatically be handled. The duplicated feature will be automatically inserted into the layer. duplicateFeatureContext stores all the layers and the featureids of the duplicated features (incl. children) maxDepth the maximum depth to duplicate children in relations, 0 is unlimited depth (in any case, limited to 100) depth the current depth, not exposed in Python referencedLayersBranch the current branch of layers across the relations, not exposed in Python, taken by copy not reference, used to avoid infinite loop

Parameters:
fieldEditabilityDependsOnFeature(layer: QgsVectorLayer | None, fieldIndex: int) bool

Returns True if the editability of the field at index fieldIndex from layer may vary feature by feature.

I.e. if the field is taken from a joined layer, the value may or may not be editable for any individual feature depending on the join’s “upsert on edit” capabilities.

Added in version 3.18.

Parameters:
Return type:

bool

fieldIsEditable(layer: QgsVectorLayer | None, fieldIndex: int, feature: QgsFeature) bool

Tests whether a field is editable for a particular feature.

Return type:

bool

Returns:

True if the field at index fieldIndex from layer is editable, False if the field is read only.

Added in version 3.10.

Parameters:
fieldIsReadOnly(layer: QgsVectorLayer | None, fieldIndex: int) bool
Return type:

bool

Returns:

True if the field at index fieldIndex from layer is editable, False if the field is read only.

If this function returns True then the editability of the field may still vary feature by feature. See fieldIsEditable() to determine this on a feature by feature basis.

Added in version 3.18.

Parameters:
getDoubleValues(layer: QgsVectorLayer | None, fieldOrExpression: str | None, selectedOnly: bool = False, feedback: QgsFeedback | None = None)

Fetches all double values from a specified field name or expression. Null values or invalid expression results are skipped.

Parameters:
  • layer (Optional[QgsVectorLayer]) – vector layer to retrieve values from

  • fieldOrExpression (Optional[str]) – field name or an expression string evaluating to a double value

  • ok – will be set to False if field or expression is invalid, otherwise True

  • selectedOnly (bool = False) – set to True to get values from selected features only

  • nullCount – optional pointer to integer to store number of null values encountered in

  • feedback (Optional[QgsFeedback] = None) -> (List[float]) – optional feedback object to allow cancellation

Returns:

list of fetched values

See also

getValues()

getFeatureDisplayString(layer: QgsVectorLayer | None, feature: QgsFeature) str
Return type:

str

Returns:

a descriptive string for a feature, suitable for displaying to the user. The definition is taken from the displayExpression property of layer.

Added in version 3.12.

Parameters:
getValues(layer: QgsVectorLayer | None, fieldOrExpression: str | None, selectedOnly: bool = False, feedback: QgsFeedback | None = None)

Fetches all values from a specified field name or expression.

Parameters:
  • layer (Optional[QgsVectorLayer]) – vector layer to retrieve values from

  • fieldOrExpression (Optional[str]) – field name or an expression string

  • ok – will be set to False if field or expression is invalid, otherwise True

  • selectedOnly (bool = False) – set to True to get values from selected features only

  • feedback (Optional[QgsFeedback] = None) -> (List[Any]) – optional feedback object to allow cancellation

Returns:

list of fetched values

getValuesIterator(layer: QgsVectorLayer | None, fieldOrExpression: str | None, selectedOnly: bool)

Create a feature iterator for a specified field name or expression.

Parameters:
  • layer (Optional[QgsVectorLayer]) – vector layer to retrieve values from

  • fieldOrExpression (Optional[str]) – field name or an expression string

  • ok – will be set to False if field or expression is invalid, otherwise True

  • selectedOnly (bool) -> (QgsFeatureIterator) – set to True to get values from selected features only

Returns:

feature iterator

guessFriendlyIdentifierField(fields: QgsFields) str

Given a set of fields, attempts to pick the “most useful” field for user-friendly identification of features.

For instance, if a field called “name” is present, this will be returned.

Assumes that the user has organized the data with the more “interesting” field names first. As such, “name” would be selected before “oldname”, “othername”, etc.

If no friendly identifier is found, the function will fallback to the first available.

Parameters:

fields (QgsFields) – list of fields to pick a friendly identifier from

Return type:

str

Returns:

field name

Added in version 3.18.

guessFriendlyIdentifierFieldV2(fields: QgsFields)

Given a set of fields, attempts to pick the “most useful” field for user-friendly identification of features.

For instance, if a field called “name” is present, this will be returned.

Assumes that the user has organized the data with the more “interesting” field names first. As such, “name” would be selected before “oldname”, “othername”, etc.

If no friendly identifier is found, the function will fallback to the first available.

Parameters:

fields (QgsFields) -> (str) – list of fields to pick a friendly identifier from

Returns:

  • field name

  • foundFriendly: set to True if the returned field name is a friendly identifier

Added in version 3.22.

impactsCascadeFeatures(layer: QgsVectorLayer | None, fids: Any, project: QgsProject | None, flags: QgsVectorLayerUtils.CascadedFeatureFlags | QgsVectorLayerUtils.CascadedFeatureFlag = QgsVectorLayerUtils.CascadedFeatureFlags())
Returns:

True if at least one feature of the fids on layer is connected as parent in at least one composition relation of the project or contains joins, where cascade delete is set. Details about cascading effects will be written to context.

Added in version 3.14.

Parameters:
makeFeatureCompatible(feature: QgsFeature, layer: QgsVectorLayer | None, sinkFlags: QgsFeatureSink.SinkFlags | QgsFeatureSink.SinkFlag = QgsFeatureSink.SinkFlags()) List[QgsFeature]

Converts input feature to be compatible with the given layer.

This function returns a new list of transformed features compatible with the input layer, note that the number of features returned might be greater than one when converting a multi part geometry to single part

The following operations will be performed to convert the input features:

  • convert single geometries to multi part

  • drop additional attributes

  • drop geometry if layer is geometry-less

  • add missing attribute fields

  • add back M/Z values (initialized to 0)

  • drop Z/M

  • convert multi part geometries to single part

Optionally, sinkFlags can be specified to further refine the compatibility logic.

Added in version 3.4.

Parameters:
Return type:

List[QgsFeature]

makeFeaturesCompatible(features: Iterable[QgsFeature], layer: QgsVectorLayer | None, sinkFlags: QgsFeatureSink.SinkFlags | QgsFeatureSink.SinkFlag = QgsFeatureSink.SinkFlags()) List[QgsFeature]

Converts input features to be compatible with the given layer.

This function returns a new list of transformed features compatible with the input layer, note that the number of features returned might be greater than the number of input features.

The following operations will be performed to convert the input features:

  • convert single geometries to multi part

  • drop additional attributes

  • drop geometry if layer is geometry-less

  • add missing attribute fields

  • add back M/Z values (initialized to 0)

  • drop Z/M

  • convert multi part geometries to single part

Optionally, sinkFlags can be specified to further refine the compatibility logic.

Added in version 3.4.

Parameters:
Return type:

List[QgsFeature]

matchAttributesToFields(feature: QgsFeature, fields: QgsFields)

Matches the attributes in feature to the specified fields.

This causes the attributes contained within the given feature to be rearranged (or in some cases dropped) in order to match the fields and order indicated by fields.

The exact behavior depends on whether or not feature has a valid fields container set (see QgsFeature.fields()). If a fields container is set, then the names of the feature’s fields are matched to fields. In this case attributes from feature will be rearranged or dropped in order to match the field names from fields.

If the feature does not have a valid fields container set, then the feature’s attributes are simply truncated to match the number of fields present in fields (or if less attributes are present in feature than in fields, the feature’s attributes are padded with NULL values to match the required length). Finally, the feature’s fields are set to fields.

Added in version 3.4.

Parameters:
validateAttribute(layer: QgsVectorLayer | None, feature: QgsFeature, attributeIndex: int, strength: QgsFieldConstraints.ConstraintStrength = QgsFieldConstraints.ConstraintStrengthNotSet, origin: QgsFieldConstraints.ConstraintOrigin = QgsFieldConstraints.ConstraintOriginNotSet)

Tests a feature attribute value to check whether it passes all constraints which are present on the corresponding field. Returns True if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. If the strength or origin parameter is set then only constraints with a matching strength/origin will be checked.

Parameters:
  • layer (Optional[QgsVectorLayer])

  • feature (QgsFeature)

  • attributeIndex (int)

  • strength (QgsFieldConstraints.ConstraintStrength = QgsFieldConstraints.ConstraintStrengthNotSet)

  • origin (QgsFieldConstraints.ConstraintOrigin = QgsFieldConstraints.ConstraintOriginNotSet) -> (bool)

valueExists(layer: QgsVectorLayer | None, fieldIndex: int, value: Any, ignoreIds: Any = QgsFeatureIds()) bool

Returns True if the specified value already exists within a field. This method can be used to test for uniqueness of values inside a layer’s attributes. An optional list of ignored feature IDs can be provided, if so, any features with IDs within this list are ignored when testing for existence of the value.

Parameters:
  • layer (Optional[QgsVectorLayer])

  • fieldIndex (int)

  • value (Any)

  • ignoreIds (Any = QgsFeatureIds())

Return type:

bool