diff --git a/services_scripts/add_new_field.py b/services_scripts/add_new_field.py index 3c72c9b..0b04858 100644 --- a/services_scripts/add_new_field.py +++ b/services_scripts/add_new_field.py @@ -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() diff --git a/services_scripts/edit_field.py b/services_scripts/edit_field.py new file mode 100644 index 0000000..b21d7d7 --- /dev/null +++ b/services_scripts/edit_field.py @@ -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()