【发布时间】:2019-06-25 21:14:05
【问题描述】:
将新的 QgsFeature 添加到现有 QgsVectorLayer 功能的属性时不会添加。
我想向已经存在的 QgsVectorLayer 添加一个新的 QgsFeature(多边形)。特征被添加到画布(显示在屏幕上),但图层对应的属性表没有更新(没有添加新创建的特征属性)
我已阅读 PyQGIS Cookbook 和相关 StackOverflow 问题,但代码无法正常工作,我不知道我缺少什么。
layer = self.projectInstance.mapLayersByName('draba_obcina')[0]
pr = layer.dataProvider()
points = [QgsPointXY(0, 0), QgsPointXY(0, 1), QgsPointXY(1, 0), QgsPointXY(0, 0)]
poly = QgsFeature(layer.fields())
#if i set OGC_FID i get SQLite error: UNIQUE constraint failed (although there is no entry with OGC_FID = 3640)
#poly.setAttribute ("OGC_FID", 3640)
poly.setAttribute ("tip_spr", None)
poly.setAttribute ("id", None)
poly.setAttribute ("sif_upr", None)
poly.setAttribute ("id_upr", None)
poly.setAttribute ("vrsta_dr", None)
poly.setAttribute ("vrsta_pov", None)
poly.setAttribute ("nac_dol", None)
poly.setAttribute ("nat_dol", None)
poly.setAttribute ("usklajenost_zk", None)
poly.setAttribute ("graf_pov", None)
poly.setAttribute ("d_spr", None)
poly.setAttribute ("d_vir", None)
poly.setAttribute ("vrsta_el", None)
poly.setAttribute ("opis", "I was created by plugin")
poly.setAttribute ("createdtime", "2019-06-25 18:51:34")
poly.setAttribute ("kat", "10")
poly.setGeometry(QgsGeometry.fromPolygonXY([points]))
res, outFeats = pr.addFeatures([poly])
layer.updateExtents()
layer.commitChanges()
layer.reload()
pr.addFeatures([poly]) 返回 (res == True) 并且 (outFeats 长度为 1) 这对我来说意味着添加该功能是成功的。
不会抛出任何错误。
但是新特性只显示在画布上,没有属性添加到属性表中。
【问题讨论】: