1

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)

1 Answer 1

3

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

provider.select(provider.attributeIndexes() )
while provider.nextFeature(inFeat):
    ...
2
  • 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
    Commented Jan 28, 2013 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
    Commented Jan 28, 2013 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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