I have a working script that builds rectangles from a CSV using @Kadir Sahbaz's answer and @Ben W's answer
I'm wanting to pass non-geometry attributes as well. This runs and creates the fields but with NULL
values:
srcFile = "D:\\Data\\filename.csv"
layer = QgsVectorLayer("Polygon?crs=EPSG:2193", "Polygons", "memory")
QgsProject.instance().addMapLayer(layer)
provider = layer.dataProvider()
provider.addAttributes([QgsField('ViewName',QVariant.String, '', 50, 0),
QgsField('FigName',QVariant.String, '', 10, 0)])
layer.updateFields()
with open(srcFile,'r') as infile:
rect = infile.readlines()
for b in rect[1:]:
parts = b.split(',')
#### Coordinates coming from CSV ####
xMin = float(parts[2])
yMin = float(parts[3])
xMax = float(parts[4])
yMax = float(parts[5])
rect = QgsRectangle(xMin, yMin, xMax, yMax)
polygon = QgsGeometry.fromRect(rect)
feature = QgsFeature()
feature.setGeometry(polygon)
provider.addFeatures([feature])
fields = QgsFields()
feature.setFields(fields)
feature['ViewName'] = parts[0]
feature['FigName'] = parts[-2]
provider.addAttributes(fields)
layer.updateFields()
I'm still getting NULL
values. FWIW...if I run @Ben W's code, change the with statement to:
with edit(layer):
print(parts[0],parts[-2])
provider.addFeatures([feature])
t = provider.changeAttributeValues({feature.id(): {f1: parts[0], f2: parts[-2]}})
print(t)
The values from the CSV are appearing and .changeAttributeValues
appears to running properly: