I've been visiting and revisiting the page on geometry handling in the PyQGIS Cookbook: http://documentation.qgis.org/2.0/en/docs/pyqgis_developer_cookbook/geometry.html but can't seem to figure out how to get the polygon to draw from the Python console. Can anyone help?
it is not realy complicated, look at Memory provider in vector: :
- a point is created with
QgsPoint(x,y)
andQgsGeometry.fromPoint(QgsPoint(x,y))
- a line is created with two points:
QgsGeometry.fromPolyline([QgsPoint(x1,y1),QgsPoint(x2,y2)]))
- a polygon is created with a list of points:
QgsGeometry.fromPolygon([[QgsPoint(x1,y1),QgsPoint(x2,y2), QgsPoint(x3,y3)]])
1) two points:
# create a memory layer with two points
layer = QgsVectorLayer('Point', 'points' , "memory")
pr = layer.dataProvider()
# add the first point
pt = QgsFeature()
point1 = QgsPoint(50,50)
pt.setGeometry(QgsGeometry.fromPoint(point1))
pr.addFeatures([pt])
# update extent of the layer
layer.updateExtents()
# add the second point
pt = QgsFeature()
point2 = QgsPoint(100,150)
pt.setGeometry(QgsGeometry.fromPoint(point2))
pr.addFeatures([pt])
# update extent
layer.updateExtents()
# add the layer to the canvas
QgsMapLayerRegistry.instance().addMapLayers([layer])
2) the line connecting the two points
layer = QgsVectorLayer('LineString', 'line' , "memory")
pr = layer.dataProvider()
line = QgsFeature()
line.setGeometry(QgsGeometry.fromPolyline([point1,point2]))
pr.addFeatures([line])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
3) a polygon covering the points
layer = QgsVectorLayer('Polygon', 'poly' , "memory")
pr = layer.dataProvider()
poly = QgsFeature()
points = [point1,QgsPoint(50,150),point2,QgsPoint(100,50)]
# or points = [QgsPoint(50,50),QgsPoint(50,150),QgsPoint(100,150),QgsPoint(100,50)]
poly.setGeometry(QgsGeometry.fromPolygon([points]))
pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
-
Changes in QGIS 3.0 and onward:
For QGIS 3.0 and onward the above workflow is still correct, but certain functions have changed. See https://qgis.org/api/api_break.html
To update the above code, change following functions:
QgsPoint -> QgsPointXY
QgsfromPoint -> QgsfromPointXY
QgsfromPolyline -> QgsfromPolylineXY
QgsfromPolygon -> QgsfromPolylineXY
QgsfromPolyline -> QgsfromPolylineXY
QgsMapLayerRegistry -> QgsProject
-
Thank you so much for the code. I was wondering how can I get rid of CRS selection dialog after I run the code? – wannik Jun 13 '14 at 4:31
-
Just select the CRS in the layer definition :
QgsVectorLayer('Polygon?crs=epsg:2154', 'poly' , "memory")
for instance (here EPSG 2154 is for Lambert 93 projection, standard in Metropolitan France, but you can put whatever you want)