PyQGIS是QGIS提供的Python语法二次开发包。它提供了常用的各类操作QGIS的功能。如添加图层、要素绘制、数据访问等等。
本文介绍使用PyQGIS修改指定矢量层要素数据的方法。
示例代码和解释说明如下所示:
# 1.获取test_line矢量图层
# 此处假设没有同名图层。
layers = QgsProject.instance().mapLayersByName('test_line')
layer = layers[0]
# 2.找到待修改的字段
field_idx = layer.fields().indexOf('changed_field_name')
new_value = 2
with edit(layer):
# 3.遍历所有选中的要素
for feat_id in layer.selectedFeatureIds():
layer.changeAttributeValue(feat_id, field_idx, new_value)
# 如需获取所有要素,请参考如下代码
# with edit(layer):
# for feat in layer.getFeatures():
# layer.changeAttributeValue(feat.id(), field_idx, new_value)
更多PyQGIS使用问题,欢迎留言或联系我们。转载须注明出处。