[Qgis-user] QgsVectorLayerDataProvider problem?
Gary Smith
gary.smith.rsa at gmail.com
Fri Jan 14 11:39:43 PST 2011
Hello,
I am not sure whether this is the right forum but extensive Google
searches have not helped. I am writing a plugin to convert the segments
of a polyline to a layer of individual 2 vertex line features.
This is the code I used to do the job
feat = QgsFeature()
p = 0
while p < cl.featureCount():
cl.featureAtId(p, feat, True, True)
geom0 = QgsGeometry(feat.geometry())
vl = QgsVectorLayer("LineString", "Mylines", "memory")
provider = vl.dataProvider()
provider.addAttributes( [ QgsField( "id" , QVariant.String),
QgsField( "agl" , QVariant.String) ])
pnt10 = QgsPoint( geom0.vertexAt(0) )
segfeat = QgsFeature()
itr = 1
while ( QgsPoint( geom0.vertexAt(itr) ) <> QgsPoint(0,0) ):
pnt10 = QgsPoint( geom0.vertexAt(itr -1) )
pnt11 = QgsPoint( geom0.vertexAt(itr) )
newGeom = QgsGeometry.fromPolyline( [ pnt10, pnt11 ] )
segfeat.setGeometry( newGeom )
segfeat.setAttributeMap( { 0 : QVariant( str(itr) ), 1 :
QVariant( str(agl) ) } )
provider.addFeatures( [segfeat] )
itr += 1
p += 1
vl.commitChanges()
QgsMapLayerRegistry.instance().addMapLayer(vl)
It appears to work fine until I need to make use of the data in the
attributes.
To do this I use the following code:
...
p = 0
while p < self.cl.featureCount():
feat = QgsFeature()
self.cl.featureAtId(p, feat, True, True)
attmap = feat.attributeMap()
attid = attmap[0].toString()
agl = attmap[1].toString()
geom0 = QgsGeometry(feat.geometry())
pnt10 = QgsPoint(geom0.vertexAt(0))
...
This code works fine on features that I create manually through the QGIS
user interface. But I get an error on the line with layers which I have
created above
The error is raised by the line
attmap = feat.attributeMap()
The error appears to be because the featureAtId function is returning
null objects and I think it is because the way I am using the provider
does not create feature id's in an orderly fashion.
Please help.
Thanks
Gary
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20110114/0bd69fa0/attachment.html>
More information about the Qgis-user
mailing list