6

Feel like I've been banging my head against the wall here. I'm writing a plugin. As part of the functionality, I have need to programmatically add a list of annotations to the map. What I have: list of coordinates (selected using QgsMapToolEmitPoint), list of corresponding plaintext notes.

Now, I've been trying to use either QgsAnnotationLayer or QgsAnnotationManager to create these annotations.

Code for AnnotationLayer:

    <<in constructor>>
    self.notelayer = QgsAnnotationLayer(name ="Annotations", options = QgsAnnotationLayer.LayerOptions)

    <<inside a method>>

    self.notelayer.clear()
    
    for i in range(len(self.xydata)):
        annotation = QgsAnnotationPointTextItem.create()

        annotation.setText(self.xynotes[i])
        annotation.setPoint(QgsPointXY(self.xydata[i][0],self.xydata[i][1]))

        QgsProject.instance().annotationManager().addAnnotation(annotation)

        self.notelayer.addItem(annotation)

xydata has the coordinates in float, and xynotes has the plaintext. I was getting an insufficient arguments error with this, so I tried using annotation manager instead. That itself had issues.

What I need is a simple example of how to actually use them to make and manage annotations. I couldn't find any examples on the web.

1 Answer 1

10

You are only missing a couple of things- to pass a QgsCoordinateTransformContext object to the LayerOptions constructor, and to add the annotation layer to the project.

QgsAnnotationLayer inherits from QgsMapLayer so you can add it to the project like any other map layer.

Here is a minimal example which you will have to adapt only slightly to implement inside your plugin:

xy_notes = ['Surfing', 'Fishing', 'Camping', 'Skiing', 'Hiking']
xy_data = [(16035000, -4640000), (14668973, -1375954), (12679771, -2523962), (16509000, -4370100), (16914498, -3353025)]

notelayer = QgsAnnotationLayer('Annotations', QgsAnnotationLayer.LayerOptions(QgsProject.instance().transformContext()))

for i in range(len(xy_notes)):
    a = QgsAnnotationPointTextItem(xy_notes[i],
                                    QgsPointXY(xy_data[i][0], xy_data[i][1]))
    a_id = notelayer.addItem(a)
    
QgsProject.instance().addMapLayer(notelayer)

Results:

enter image description here

2
  • Thank you so much! Simple code examples help so much, thank you.
    – quagzlor
    Feb 12, 2022 at 11:33
  • 1
    No problem, @quagzlor. You're most welcome :-)
    – Ben W
    Feb 12, 2022 at 11:37

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.