Graphics Reference
In-Depth Information
Adding Points
The following map tool allows the user to add a new Point feature to the given layer:
class AddPointTool(QgsMapTool):
def __init__(self, canvas, layer):
QgsMapTool.__init__(self, canvas)
self.canvas = canvas
self.layer = layer
self.setCursor(Qt.CrossCursor)
def canvasReleaseEvent(self, event):
point = self.toLayerCoordinates(self.layer,
event.pos())
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPoint(point))
self.layer.addFeature(feature)
self.layer.updateExtents()
As you can see, this straightforward map tool sets the mouse cursor to a cross shape, and
when the user releases the mouse over the map canvas, a new QgsGeometry object is
created that represents a point at the current mouse position. This point is then added to the
layer using layer.addFeature() , and the layer's extent is updated in case the newly
added point is outside the layer's current extent.
Of course, this map tool is only a starting point—you would typically add code to set the
feature's attributes and to notify the application that a point has been added. However, as
you can see, allowing the user to create a new Point feature is quite straightforward.
Search WWH ::




Custom Search