2

I'm able to add an annotation in QGIS 3.10 it works with this code

from qgis.core import QgsTextAnnotation, QgsPointXY, QgsCoordinateReferenceSystem, QgsAnnotationManager
from qgis.gui import QgsMapCanvasAnnotationItem
from PyQt5.QtGui import QTextDocument
from PyQt5.QtCore import QSizeF,QPoint

annot = QgsTextAnnotation()
annot.setFrameSize(QSizeF(100, 50))
annot.setMapLayer(layer)
annot.setFrameOffsetFromReferencePoint(QPoint(10, 10))
annot.setDocument(QTextDocument('TEST'))

# X and Y are defined previously
annot.setMapPositionCrs(QgsCoordinateReferenceSystem(layer.crs()))
annot.setMapPosition(QgsPointXY(x, y))

QgsMapCanvasAnnotationItem(annot, qgis.utils.iface.mapCanvas())

The annotation is added but I can't modify it in the GUI or delete it. How can I do it? There is an other thing to add in my code?

  • The code seems fine. Did you activate the "Annotation" tool (from the "Attributes" toolbar) before trying to edit the annotation in the GUI? – Jake Mar 24 at 8:00
  • Yes i did. I can get the form to edit but when i push the ok button, the modification is not applied – TrsBar Mar 24 at 8:49
  • 1
    I believe you should use the QgsAnnotationManager for keeping track of the annotations. Can you try replacing your last line with QgsProject.instance().annotationManager().addAnnotation(annot) – Jake Mar 24 at 11:02
  • 1
    Thanks @Jake it works great ! That was the trick. – TrsBar Mar 24 at 12:04
2

To add the annotation to the canvas, you should use the QgsAnnotationManager.

In your case, you could replace the last line of your code with

QgsProject.instance().annotationManager().addAnnotation(annot)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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