Saturday, 2 July 2016

qgis - How to create memory layer and populate fields?


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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...