1

Recently I learned how to create a point in the map independently from any layer, using QgsVertexMarker. Now, I would like to put a label beside it, using Python. However, I do not see an option 'label' or something like that belonging to the class QgsVertexMarker.

How to do this?

0

1 Answer 1

2

I think the closest you can get to labeling a vertex marker would be to use a QgsTextAnnotation.

So following on from your previous question, and based on Fran Raga's answer here and Stefan's question (for QGIS 2.X) here,

you could do something like:

canvas = iface.mapCanvas()

lon = 131.2
lat = -12.5

pnt = QgsPointXY(lon, lat)

m = QgsVertexMarker(canvas)
m.setCenter(pnt)
m.setColor(QColor('Black'))
m.setIconType(QgsVertexMarker.ICON_CIRCLE)
m.setIconSize(15)
m.setPenWidth(1)
m.setFillColor(QColor(0, 200, 0))

sym = QgsMarkerSymbol()
sym.setSize(0)
txt = QTextDocument('Point A')
lbl = QgsTextAnnotation(canvas)
lbl.setDocument(txt)
lbl.setFrameSize(QSizeF(50.0, 25.0))
lbl.setMapPosition(pnt)
lbl.setFrameSize(QSizeF(txt.size().width(),txt.size().height()))
lbl.setFrameOffsetFromReferencePoint(QPointF(10, 5))
lbl.setMarkerSymbol(sym)
i = QgsMapCanvasAnnotationItem(lbl, canvas)

#canvas.scene().removeItem(m)
#canvas.scene().removeItem(i)

Result:

enter image description here

You can play around with the map position and offset etc to move the annotation item around.

The documentation for the classes can be found here:

https://qgis.org/api/classQgsAnnotation.html

https://qgis.org/api/classQgsTextAnnotation.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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