2

I've been searching some example about how to draw polylines and polygons on the map composer using PyQGIS, but I couldn't find anything. Could someone show me some code to learn?

2

When you are stuck, you should look at QGIS API documentation, PyQGIS documentation and Python tests directory from QGIS repository e.g https://github.com/qgis/QGIS/tree/master/tests/src/python

For the first two links for your use cases, you should look at classes containing QgsLayout string (by doing a textual search)

You may wonder how I've guessed I should look at QgsLayoutItemPolygon or QgsLayoutItemPolyline? I've drawn manually the line and the polygon and selected them individually in the layout. Then, I've run the 4 first lines from below recipe in the QGIS Python console to know which class was involved. The other parts are mainly standalone version of the tests directory for your purpose.

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName('demo') # Use your layout name instead of demo
layout.selectedLayoutItems()

# Recipe from layout Polygon
# Mainly borrowed from https://github.com/qgis/QGIS/blob/master/tests/src/python/test_qgslayoutpolygon.py
polygon1 = QPolygonF()
polygon1.append(QPointF(0.0, 0.0))
polygon1.append(QPointF(100.0, 0.0))
polygon1.append(QPointF(200.0, 100.0))
polygon1.append(QPointF(100.0, 200.0))

layoutItemPolygon = QgsLayoutItemPolygon(polygon1, layout)
layout.addLayoutItem(layoutItemPolygon)

# Recipe from layout Polyline
# Mainly borrowed from https://github.com/qgis/QGIS/blob/master/tests/src/python/test_qgslayoutpolyline.py
polygon2 = QPolygonF()
polygon2.append(QPointF(50.0, 150.0))
polygon2.append(QPointF(150.0, 80.0))
polygon2.append(QPointF(250.0, 100.0))
polygon2.append(QPointF(10.0, 200.0))

layoutItemPolyline = QgsLayoutItemPolyline(polygon2, layout)
layout.addLayoutItem(layoutItemPolyline)
1
  • 1
    Thats just what i needed! I thank you very much for the advice, I will always keep it in mind. I'm really new to pyqgis development and you've given me a big push. – Perla Rdz Jun 3 '20 at 19:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.