Add a module for editting a layer's field (computing area)

This commit is contained in:
Alireza Adli 2024-03-12 16:01:23 -04:00
parent 0082c8c9e7
commit 6c6d46255c
2 changed files with 28 additions and 2 deletions

View File

@ -5,10 +5,10 @@ from qgis.PyQt.QtCore import QVariant
layer = QgsVectorLayer(
'C:/Users/a_adli/PycharmProjects/'
'hydroquebec_archetype_gispy/data/'
'output_data/multi_to_single/multi_to_single.shp', "your_layer", "ogr")
'output_data/multi_to_single/multi_to_single.shp', 'your_layer', 'ogr')
functionalities = layer.dataProvider().capabilities()
if functionalities & QgsVectorDataProvider.AddAttributes:
new_field = QgsField("Area", QVariant.Double)
new_field = QgsField("Area", QVariant.Double)
layer.dataProvider().addAttributes([new_field])
layer.updateFields()

View File

@ -0,0 +1,26 @@
"""
This code is to show how to edit a layer's field. In this example,
the area of each record is calculated and will be assigned to the
field (here 'Area')
"""
from qgis.core import QgsVectorLayer, QgsExpressionContext, QgsExpressionContextUtils
layer = QgsVectorLayer(
'C:/Users/a_adli/PycharmProjects/'
'hydroquebec_archetype_gispy/data/'
'output_data/multi_to_single/multi_to_single.shp', 'your_layer', 'ogr')
layer.startEditing()
idx = layer.fields().indexFromName('Area')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
for feature in layer.getFeatures():
area = feature.geometry().area()
feature[idx] = area
layer.updateFeature(feature)
layer.commitChanges()