4

I would like to get the name of the map tool currently in use in QGIS, so that my plugin can react accordingly. The idea would be to do something a bit like akbargumbira's answer to that other question, but for map tools instead of map layers. It should look like that :

if QGisMapTool.instance().value()=="Identify":
    do something
elif QGisMapTool.instance().value()=="Measure":
    do something else
(...)

I've searched on Stack and in the API documentation, but I have been unable to find the appropriate method so far.

Mefimefi
  • 586
  • 1
  • 6
  • 19
  • 2
    you can use iface.mapCanvas().mapTool().toolName () for obtain the current maptool name .https://qgis.org/api/classQgsMapTool.html – Fran Raga Nov 29 '17 at 14:46
  • 1
    facepalm I ctrl+F'ed the page you link for "value", "instance", "attribute", "object" but not for "name". My mistake. Thank you! – Mefimefi Nov 29 '17 at 14:56

1 Answers1

5

One issue with trying to get the name of the tool is that not all tools have a name to begin with. For example, when using the Select Feature(s) tool, it's tool name is:

iface.mapCanvas().mapTool().toolName()
>>> u'Select features'

But when using the Select Features by Polygon:

iface.mapCanvas().mapTool().toolName()
>>> u''

Some tools don't have an individual name.


One method is to instead get the class of the current map tool and use this in an if statement:

from qgis.gui import QgsMapTool, QgsMapToolIdentify

if isinstance(iface.mapCanvas().mapTool(), QgsMapToolIdentify):
    # do something
elif isinstance(iface.mapCanvas().mapTool(), QgsMapTool):
    # do something

Note that all map canvas tools fall into the QgsMapTool class (as mentioned by @FranciscoRaga and referenced in the image below). Therefore in the above code, if the first if statement is not true then it will pass to the elif.

QgsMapTools

Joseph
  • 75,746
  • 7
  • 171
  • 282