In another post has been discussed how to draw marker in QGIS map canvas. Maybe you have a question what about polyline and polygon? How to draw those in QGIS using Python? This tutorial will give the answer.
To draw a polyline we are using QgsRubberBand class. But Firstly we need to initiate the canvas first using QGIS interface.
Using QgsPoints class then a list of points coordinate for a polyline are defined. Then we set the geometry with QgsGeometry class and set the defined points as the argument. Finally customize how the polyline looks like. Set it's color and the width of the polyline. The complete code as follow:
Similar with polyline, we also use QgsRubberBand class to draw polygon. But in defining the point list we are using QgsPointXY class instead of QgsPoint. Then we customize the outline color of the polygon, it's widht and fill color. The complete code to draw polygon can be seen below.
Figure 1 shows the polyline and polygon from the code above. We can see a red polyline and a yellow polygon with blue outline in QGIS map canvas. To show and hide the drawing object use hide and show method. Type it in the console.
|Figure 1. Polyline and Polygon drawing|