Seems like a basic operation using PyQGIS but can't see what I am missing. I want to create a memory layer with the exact same features and attributes from a shapefile. I have looked several posts such as:
The following script creates a memory layer, gets the correct fields and correct number of features but it doesn't populate the fields with data:
input = "C:/Users/Me/Desktop//example.shp"
layer = QgsVectorLayer(example,"line","ogr")
temp = QgsVectorLayer("LineString?crs=epsg:4326", "result", "memory")
temp_data = temp.dataProvider()
temp.startEditing()
layer_fields = layer.dataProvider().fields().toList()
attr = layer.dataProvider().fields().toList()
temp_data.addAttributes(attr)
temp.updateFields()
feat = QgsFeature()
for elem in layer.getFeatures():
feat.setGeometry(elem.geometry())
feat.setAttributes(attr)
temp.addFeatures([feat])
temp.updateExtents()
temp.commitChanges()
QgsMapLayerRegistry.instance().addMapLayer(temp)
Answer
Hmm, you set attributes to a list of fields instead a list of values. Try this:
feat.setAttributes(elem.attributes())
No comments:
Post a Comment