[Qgis-user] Adding QgsLayoutItemPolyline to the print layout legend

Nyall Dawson nyall.dawson at gmail.com
Sat Oct 19 17:02:02 PDT 2024


On Sun, 20 Oct 2024, 9:16 am Asim al-sofi via QGIS-User, <
qgis-user at lists.osgeo.org> wrote:

> Hi all
> Iam trying to add legend to the print layout of a polyline that have been
> created using QgsLayoutItemPolyline.
> I managed to draw the polyline on the map composer and play with its
> properties, but could not add the corresponding line to the legend.
> Any ideas/suggestions?
> The code that corresponds to the legend is:
>
> 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)
>
> props = {}
> props["color"] = "green"
> props["style"] = "solid"
>
> symbol = QgsLineSymbol.createSimple(props)
> layoutItemPolyline.setSymbol(symbol)
> legend = QgsLayoutItemLegend(layout)
> legend.setAutoUpdateModel(False)
> root = legend.model().rootGroup()
> legend = QgsLayoutItemLegend(layout)
> legend.setTitle("Legend")
> legend.setAutoUpdateModel(False)
> legend.setLinkedMap(map)
> legend.setLegendFilterByMapEnabled(True)
> layout.addLayoutItem(legend)
> legend.attemptMove(QgsLayoutPoint(235, 36, QgsUnitTypes.LayoutMillimeters))
>

Add a temporary memory layer to the project with the same line symbol as
the polyline item, then add that temporary layer to the legend.

(This trick also works for adding additional points or fills to a legend)

Nyall


>
> Thanks in advance
> Kind regards,
> Asim
> _______________________________________________
> QGIS-User mailing list
> QGIS-User at lists.osgeo.org
> List info: https://lists.osgeo.org/mailman/listinfo/qgis-user
> Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20241020/84e621d8/attachment.htm>


More information about the QGIS-User mailing list