I'm attempting to add a polygon to a new layer using PyQGIS in QGIS 3.14. Adapting some examples from questions and answers here and here. I believe I have successfully created the polygon from an array of (four) input points and then a feature that contains the polygon.

I have then created a layer for the feature in the CRS I desire but cannot work how to get the feature into the layer. Code so far below.

# Attach modules 
from qgis.core import *                        # attach main QGIS library
from qgis.utils import *                       # attach main python library
import os                                      # attach operating system library

# Create an array [] object with the polygon vertices
vrtcs = []

# Create a polygon from the coordinates
ply_01 = QgsGeometry.fromPolygonXY([vrtcs])

# Create a feature object then put the polygon into the feature
ftr = QgsFeature()

# Create a layer for the feature, in the desired CRS
lyr = QgsVectorLayer('Polygon?crs=epsg:29194', '200905_Bdy',"org")

# Set an object for the data provider for the layer
prv = lyr.dataProvider()                               

# Add the feature to the layer using this provider (fails)

2 Answers 2


Change 'org' into 'memory' and add Prj = QgsProject.instance() line before using Prj.


# Create a layer for the feature, in the desired CRS
lyr = QgsVectorLayer('Polygon?crs=epsg:29194', '200905_Bdy', "memory")
Prj = QgsProject.instance()  # ADD THIS LINE

Since you add one layer, you can use Prj.addMapLayer(lyr) instead of Prj.addMapLayers([lyr]).

  • Kadir - thanks for the reply. I did set a reference Prj = QgsProject.instance() higher up in the script but forgot to include it in the post. However this did not work as I still get the error TypeError: QgsProject.addMapLayers(): argument 1 has unexpected type 'QgsVectorLayer' when I run the line Prj.addMapLayers(lyr) Commented Sep 8, 2020 at 6:26
  • You should use addMapLayer, not addMapLayers. ...Layers([lyr]) -> ...Layer(lyr) Commented Sep 8, 2020 at 6:44
  • Thanks, Kadir that works no to get it to display! Commented Sep 8, 2020 at 6:47
  • I found using prv.addFeatures([ftr]) more meaningful as the console reports on execuation 'True, [<qgis._core.QgsFeature object at 0x000002116B69A288>])', while using prv.addFeatures(ftr) there console reports is '(True, [])' , the latter being a bit crytpic for the novice scripter Commented Sep 8, 2020 at 23:03

You must start editing before adding the feature to the layer and commit the changes after you are done:

if feature.isValid():
    commited = layer.commitChanges()
    if commited:
        return True
        return False

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.