5

I am attempting to create a simple polygon on QGIS 3.14 using PyQGIS by adapting the code from How to draw polygons from the python console?.

I am running into an error with the setGeometry line where the function fromPolylineXY appears to need a QgsPointXY object but the pts object is a list.

Code so far is listed below.

tmp = QgsVectorLayer('Polygon?crs=epsg:29194', '200905_Bdy',"org") #Layer for polygon 
prv = tmp.dataProvider()                               #Data object for polygon layer
ply01 = QgsFeature()                                   #Object for polygon
# Object with polygon verticies
pts = [QgsPointXY(396100,8969000),QgsPointXY(396100,8973900),QgsPointXY(397900,8973900),QgsPointXY(397900,8969000)]
ply01.setGeometry(QgsGeometry.fromPolylineXY([pts]))
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
user2627043
  • 403
  • 3
  • 12

1 Answers1

6

You should use fromPolygonXY instead of fromPolylineXY to create a polygon. Use ply01.setGeometry(QgsGeometry.fromPolygonXY([pts]))

If you want to create a polyline before creating a polygon, you should know this: pts object is a list. And fromPolylineXY expects "a list of QgsPointXY". When you use extra brackets like [pts], it will be a list of list of QgsPointXY ([[QgsPointXY, QgsPointXY, ...]]). To create o polyline you should remove the bracket in fromPolylineXY([pts]) to get a list of QgsPointXY. Just use fromPolylineXY(pts).

Briefly;
To create a polygon from point list: QgsGeometry.fromPolygonXY([pts])
To create a polyline from point list: QgsGeometry.fromPolylineXY(pts)

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
  • Kadir, thank you for you your response which has solved my issue. I'm assuming the use of square brackets to make a list is python code convention? Or is it something unique to pyQGIS - as you can probably guess I'm new to both – user2627043 Sep 06 '20 at 00:09
  • Yes. It is a python rule. – Kadir Şahbaz Sep 06 '20 at 06:31