2

In QGIS 3.12, I'm trying to get a feature on the mapCanvas from a plugin trough a pushButton. I used the code from here but it doesn't work in the plugin although it works fine in the QGIS python Editor.

from qgis.gui import QgsMapToolIdentifyFeature

def onFeatureIdentified(feature):
    fid = feature.id()
    print ("feature selected : " + str(fid))

layer = iface.activeLayer()
mc=iface.mapCanvas()
mapTool = QgsMapToolIdentifyFeature(mc)
mapTool.setLayer(layer)
mc.setMapTool(mapTool)
mapTool.featureIdentified.connect(onFeatureIdentified)

I tried to insert it in my plugin:

Connecting the button:

self.dlg.pbAddFeature.clicked.connect(self.addFeature)

def onFeatureIdentified(feature):
    fid = feature.id()
    print ("feature selected : " + str(fid))

def addFeature(self):
    layer = myLayer
    mc=iface.mapCanvas()
    mapTool = QgsMapToolIdentifyFeature(mc)
    mapTool.setLayer(layer)
    mc.setMapTool(mapTool)
    mapTool.featureIdentified.connect(self.onFeatureIdentified)

But nothing happens.

The only way I found to have an action was to extract the maptool as a property in my plugin.

Class MyQGISPlugin
    mapTool = None

then connecting the onFeatureIdentified method in the run method:

self.mapTool = QgsMapToolIdentifyFeature(self.iface.mapCanvas())
self.mapTool.featureIdentified.connect(self.onFeatureIdentified)

then defining the onFeatureIdentified method:

def onFeatureIdentified(feature):
    print(type(feature))

and then defining the press Button method:

def addFeature(self):
    self.mapTool.setLayer(self.myLayer)
    self.iface.mapCanvas().setMapTool(self.mapTool)

When In click the pushButton on my dialog, the cursor changes and I can click in myLayer but it prints me <class 'my_qgis_plugin.my_qgis_plugin.MyQGISPlugin'> instead of a feature. And it prints AttributeError: 'MyQGISPlugin' object has no attribute 'id' when I use the first onFeatureIdentified to print the feature's id.

  • 2
    Try to change def onFeatureIdentified(feature): to def onFeatureIdentified(self, feature): If I'm not wrong your onFeatureIdentified is a method of your plugin: it expects def myfunction(self, arg1, arg2, ...): – ThomasG77 Jun 17 at 22:40
  • Thank you, that was exactly the problem. I was blinded by the QgsMapToolIdentifyFeature code implementation. – aurel_nc Jun 18 at 0:12
  • 2
    @aurel_nc Made an answer – ThomasG77 Jun 18 at 2:18
3

You should change your code by replacing def onFeatureIdentified(feature): with def onFeatureIdentified(self, feature):

If I'm not wrong your onFeatureIdentified is a method of your plugin: it expects something like def myfunction(self, arg1, arg2, ...):

| improve this answer | |
0

I found an interesting implementation of QgsMapToolIdentifyFeature here

| improve this answer | |

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.