4

I have created a memory polygon layer in my QGIS plugin. Then I added a buffer based on a point. I can see the ploygon memory layer in the map canvas and I can save it to a shapefile from the main GUI. But when I try to save it with the following code, it doesn't work. What am I doing wrong?

(please forgive my beginner-style coding)

uri = "Polygon?field=id:integer&index=yes&crs=27700"
self.polyLayer = QgsVectorLayer(uri, "Study area", "memory")
self.provider = self.polyLayer.dataProvider()
QgsMapLayerRegistry.instance().addMapLayer(self.polyLayer)

# create buffer feature
featurepoly = QgsFeature()
featurepoly.setGeometry(QgsGeometry.fromPoint(QgsPoint(self.point.x(),self.point.y())).buffer(200,1000, 1, 1, 1.0))
self.polyLayer.startEditing()
self.polyLayer.addFeature(featurepoly, True)
self.polyLayer.commitChanges()

# getting the new buffered memory layer
poly = self.iface.activeLayer()

prov = poly.dataProvider()
fields = prov.fields()

dir_poly = self.plugin_dir + '/data/poly_temp.shp'
writer = QgsVectorFileWriter(dir_poly, "CP1250", fields, prov.geometryType(),
                                     prov.crs(), "ESRI shapefile")
if writer.hasError() != QgsVectorFileWriter.NoError:
            self.iface.messageBar().pushMessage("Error when creating shapefile: ", str(writer.hasError()))

geometry = poly.geometry()
feature = QgsFeature()
feature.setGeometry(geometry)
writer.addFeature(feature)
del writer
  • Yes, It is there. – biglimp Feb 7 '15 at 17:38
2

You may need to have this at the top of your code:

from PyQt4.QtCore import *

Or it might be the path you are giving it:

http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html

that documentation just has a file name, you could give it a path instead and then it works.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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