4

I am writing a plugin that includes interaction with the map. Therefore I use a QgsMapTool. It is possible for a user to mark a point on the map. When the user clicks a red X is drawn on the mapCanvas via QgsVertexMarker.

vertex_marker = QgsVertexMarker(self.canvas)
vertex_marker.setCenter(QgsPoint(map_coordinates['x'], map_coordinates['y']))
vertex_marker.setColor(QColor(255, 0, 0))
vertex_marker.setIconSize(7)
vertex_marker.setIconType(QgsVertexMarker.ICON_X)  # ICON_BOX, ICON_CROSS, ICON_X
vertex_marker.setPenWidth(2)

This is working fine. And the red X's are displayed on the map. But I can't delete the VertexMarker. I am trying to delete the VertexMarker from the scene. I've used something like this:

vertex_items = [ i for i in iface.mapCanvas().scene().items() if issubclass(type(i), qgis.gui.QgsVertexMarker)]

for ver in vertex_items:
    if ver in iface.mapCanvas().scene().items():
        iface.mapCanvas().scene().items().remove(ver)

iface.mapCanvas().refresh()

Like this I get the used VertexMarker that are visible on the scene. But the remove function somehow doesn't remove the marker from the scene.

Is there another possibility to remove the QgsVertexMarker from the scene?

3

I found a solution. Instead of

iface.mapCanvas().scene().items().remove(ver) 

the item has to be deleted directly from the scene:

vertex_items = [ i for i in iface.mapCanvas().scene().items() if issubclass(type(i), qgis.gui.QgsVertexMarker)]

for ver in vertex_items:
    if ver in iface.mapCanvas().scene().items():
        iface.mapCanvas().scene().removeItem(ver)
2

For a standalone application (without an interface) [Wien 2.8.1] use:

canvas.scene().removeItem(vertexMarker)

Found in PyQgis Developer Cookbook/ Rubberbands and vertex markers

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.