Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I'm trying to create a new layer in QGIS based on an existing layer. The new features should have all the attributes of the corresponding features in the original layer. I've been trying to use outFeat.setAttributeMap(inFeat.attributeMap() ) similar to what Victor Olaya is doing at http://qgissextante.blogspot.de/2012/11/spliting-vector-layer.html, but all the attributes come out as NULL.

Could you tell me where the error is in my code?

def test(outputFilename):
 layer = qgis.utils.iface.activeLayer()
 provider = layer.dataProvider()
 fields = provider.fields()
 writer = QgsVectorFileWriter(outputFilename, "CP1250", fields, provider.geometryType(), provider.crs(), "ESRI Shapefile")
 inFeat = QgsFeature()
 outFeat = QgsFeature()
 inGeom = QgsGeometry()
 while provider.nextFeature(inFeat):
  point = inFeat.geometry().asPoint()
  inGeom = inFeat.geometry()
  outFeat.setGeometry(inFeat.geometry() )
  outFeat.setAttributeMap(inFeat.attributeMap() )
  writer.addFeature( outFeat )
 del writer
 newlayer = QgsVectorLayer(outputFilename, "Output", "ogr")
 QgsMapLayerRegistry.instance().addMapLayer(newlayer)

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You are missing a provider.select() method call.

provider.select(provider.attributeIndexes() )
while provider.nextFeature(inFeat):
    ...
share|improve this answer
    
Ah, thank you so much! That fixes it! (I had to add provider.select( provider.attributeIndexes() ), though, which makes sense when looking at the docs) –  Jake Jan 28 '13 at 23:33
2  
All good. Just be aware that this has changed in the latest dev build so you will have to update it in 2.0 –  Nathan W Jan 28 '13 at 23:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.