2

I've created a map tool for QGIS 2.0 Python plugin that emits a point with the click of the mouse. I'm trying to create an edit tool, adding a point feature at the emitted point while selecting another layer's feature at the same time.

The map tool was created under init like so:

def __init__(self, iface):
    …
    self.canvas = self.iface.mapCanvas()
    self.clickTool = QgsMapToolEmitPoint(self.canvas)
    …

Connected the map tool under initGui:

def initGui(self):
    …
    self.clickTool.canvasClicked.connect(self.addAndSelect)
    …

The function addAndSelect() should add a point and select features. I think my problem lies here, but I'm not sure what it is. Currently, the elements in my other layer are selected and the feature form opens, however, no feature is added to the attribute table and all info filled in on the form is lost:

def addAndSelect(self, point, button):
    layer_caps = self.myLayer.dataProvider().capabilities()
    self.feat = QgsFeature()
    pntGeom = QgsGeometry.fromPoint(point)
    self.feat.setGeometry(pntGeom)
    self.myLayer.addFeatures([self.feat], False)

    pntBuff = pntGeom.buffer((self.canvas.mapUnitsPerPixel() * 2), 0)
    rect = pntBuff.boundingBox()
    Nature_idx = self.resLayer.fieldNameIndex('Nature')
    Diam_idx = self.resLayer.fieldNameIndex('Diametre')
    self.selectList = []
    self.natureList = []
    self.diametreList = []
    iter = self.otherLayer.getFeatures()
    for feature in iter:
        if feature.geometry().intersects(rect):
            self.selectList.append(feature.id())
            self.natureList.append(feature.attributes()[Nature_idx])
            self.diametreList.append(feature.attributes()[Diam_idx])                       
    self.otherLayer.setSelectedFeatures(self.selectList)

    self.iface.openFeatureForm(self.myLayer, self.feat, False)

    self.myLayer.updateExtents()
    self.myLayer.reload()
    self.canvas.refresh()

    self.myLayer.editingStopped.connect(self.unsetMyMapTool)

The map tool is set under the run method:

def run(self):
    …
    if result == 1:
        self.canvas.setMapTool(self.clickTool)
        self.myLayer.startEditing()    

The map tool is unset with unsetMyMapTool method:

def unsetMyMapTool(self):
    self.canvas.unsetMapTool(self.clickTool)

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.