I used the polygonize tool in order to polygonize a raster layer and it worked well, but now, I would like to save this new vector layer as a temporary layer.

My code from various posts is the following :

grid = QgsVectorLayer("Polygon?crs=epsg:4326", 

#grid = self.pabs+"/1_Grids/Grid_"+str(self.id)+".shp" #non temporary layer initially used

layer = self.pabs+"/0_Inputs/LandUse/lu_{}.tif".format(self.id)

When I execute the code in the python console of Qgis I get:

'QgsVectorLayer' object has no attribute '__ getitem__'

I know that you sometimes have this problem with python class but here I don't see where the problem comes from.

I was wondering if it is linked to the fact I create an empty layer ?

I am using QGIS 2.18.10

  • You could use the None parameter as output which will save the result as a temporary layer: processing.runalg('gdalogr:polygonize',layer,"lu_majorit",None). Or to load it immediately: processing.runandload('gdalogr:polygonize',layer,"lu_majorit",None).
    – Joseph
    Jul 13, 2017 at 14:10
  • But how can I call it after ? Because I need to had some fields on it
    – J.Delannoy
    Jul 13, 2017 at 14:15
  • to add some fields, sorry
    – J.Delannoy
    Jul 13, 2017 at 14:23

2 Answers 2


Use the None parameter in the processing algorithm to create a temporary output. You can then call and add this output as a vector layer and add your fields etc.

layer = self.pabs+"/0_Inputs/LandUse/lu_{}.tif".format(self.id)
result = processing.runalg('gdalogr:polygonize',layer,"lu_majorit",None)

polygonized_layer = processing.getObject(result['OUTPUT'])
polygon_layer = iface.addVectorLayer(polygonized_layer.source(), "Grid_"+str(self.id), "ogr")
# Add your field
polygon_layer.dataProvider().addAttributes([QgsField("index", QVariant.Int)])

To source this answer comment:

python script in QGis - help using gdal.Polygonize

the third parameter needs to be an instance of the GDAL/OGR vector layer class; you're passing in an instance of the QGIS vector layer class... not the same thing!....

This should produce a temporary vector polygon layer (need to use the None value for the last parameter, this puts the result in memory):

result = processing.runalg('gdalogr:polygonize',layer,"lu_majorit", None)
polygonLayer = processing.getObject(result['OUTPUT'])

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.