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.
def onFeatureIdentified(feature):todef onFeatureIdentified(self, feature):If I'm not wrong youronFeatureIdentifiedis a method of your plugin: it expectsdef myfunction(self, arg1, arg2, ...):– ThomasG77 Jun 17 '20 at 22:40