1

I'm trying to create a polygon layer from 4 points that I have already defined. There issue here is that I'm always getting the following error:

AttributeError: type object 'QgsGeometry' has no attribute 'fromPolygon'

These are the points (printed in console):

print (points)
<QgsPoint: Point (546016.50083752069622278 4760165.85990538075566292)>
<QgsPoint: Point (535433.25716883409768343 4749582.61623669415712357)>
<QgsPoint: Point (559882.5150161839555949 4746299.84572671726346016)>
<QgsPoint: Point (549299.27134749735705554 4735716.60205803066492081)>

And here is the code that produces the error above:

layer = QgsVectorLayer(str('Polygon?crs='+crs), 'polygon' , 'memory')
prov = layer.dataProvider()
points = [H1V1p,H1V2p,H2V1p,H2V2p]
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPolygon([points]))
prov.addFeatures([feat])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
  • 1
    "fromPolygon() was renamed to fromPolygonXY()" accouring to this – BERA Sep 11 at 15:42
  • I will check it soon but you can post it as an answer and if it works I'll make green check. – César Arquero Sep 11 at 15:57
1

In the line of the @BERA comment, this solves the problem in QGIS 3.8:

The points must be created with 'QgsPointXY' (instead of 'QgsPoint').

The polygon must be created with 'fromPolygonXY' (instead of fromPolygon').

p1 = QgsPointXY(546016, 4760165)
p2 = QgsPointXY(535433, 4749582)
p3 = QgsPointXY(535833, 4749982)

layer = QgsVectorLayer('Polygon', 'polygon' , 'memory')
prov = layer.dataProvider()
points = [p1,p2,p3]
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPolygonXY([points]))
prov.addFeatures([feat])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])

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.