1

I have a script that is adapted from the book Menke - Mastering QGIS and used to draw a polygon directly on the map canvas. Now I want to expand upon that script and mirror the 'add feature' functionality. I.e. the script is supposed to take the coordinates that are stored in a list, transform them into a geometry and add the feature.

I tried the following and while I'm not getting any errors, I continue to have only a single rubber band connecting all my polygons.

Here's the code:

from PyQt4.QtCore import *
from PyQt4.QtGui import QColor
from qgis.core import QGis, QgsMapLayerRegistry
from qgis.gui import QgsMapToolEmitPoint, QgsRubberBand, QgsMapTool

# Create new virtual layer 
vlyr = QgsVectorLayer("Polygon", "temporary_polygons", "memory")
dprov = vlyr.dataProvider()

# Add field to virtual layer 
dprov.addAttributes([QgsField("name", QVariant.String),
                     QgsField("size", QVariant.Double)])

vlyr.updateFields()

# Access MapTool  
previousMapTool = iface.mapCanvas().mapTool()
myMapTool = QgsMapToolEmitPoint( iface.mapCanvas() )

# create the polygon rubber band associated to the current canvas
myRubberBand = QgsRubberBand( iface.mapCanvas(), QGis.Polygon )

# set rubber band style
color = QColor(78, 97, 114)
color.setAlpha(190)
myRubberBand.setColor(color)

# create empty list to store coordinates 
coordinates = []


# Create Feature 
poly = QgsFeature() 


# define function draw rubberband
def drawBand( currentPos, clickedButton ):
    iface.mapCanvas().xyCoordinates.connect( drawBand )

    if myRubberBand and myRubberBand.numberOfVertices():
        myRubberBand.removeLastPoint()
        myRubberBand.addPoint( currentPos )

    if clickedButton == Qt.RightButton: 
        pass


# define function mouseclick
def mouseClick( currentPos, clickedButton ):
    if clickedButton == Qt.LeftButton:
        myRubberBand.addPoint( currentPos )
        coordinates.append(currentPos)
        print coordinates
    if clickedButton == Qt.RightButton:

        dprov.addFeatures([poly])
        poly.setGeometry(QgsGeometry.fromPolygon ([coordinates]))
        vlyr.updateExtents()
        iface.mapCanvas().refresh()
        QgsMapLayerRegistry.instance().addMapLayers([vlyr])
        del coordinates[:]


myMapTool.canvasClicked.connect( mouseClick )
iface.mapCanvas().setMapTool( myMapTool )

Also, I tried to have a look at the code of the qgis 'add feature' tool, but was unable to find it within the repository. Perhaps someone could point me into the right direction here as well?

Your Answer

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

Browse other questions tagged or ask your own question.