You set feature fields to empty QgsFields
.
fields = QgsFields() # fields is empty
feature.setFields(fields) # you set the empty fields
Instead, pass layer.fields()
to QgsFeature
.
feature = QgsFeature(layer.fields())
You also get NULL
values, because you add the feature to the layer (provider.addFeatures([feature])
) before you populate the fields.
Use this script:
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:
rows = infile.readlines()
for r in rows:
parts = r.split(',')
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(layer.fields())
feature.setGeometry(polygon)
feature['ViewName'] = parts[0]
feature['FigName'] = parts[-2]
provider.addFeatures([feature])
Sample CSV:
1,0, 1804512.8556, 5453390.58088, 1813512.8556, 5461390.58088, yedi1, sekiz1, dokuz1
2,0, 1814512.8556, 5473390.58088, 1823512.8556, 5471390.58088, yedi2, sekiz2, dokuz2
Result: