[GIS] `NameError: name `qgis` is not defined` in QGIS Plugins

pyqgisqgis-3qgis-plugins

In the QGIS (2.99) Python Console, the name/variable qgis seems to be automatically defined.

However, in writing a plugin, there is an error whenever I refer to qgis. For example, in I have qgis.iface.mapCanvas() in my Plugin's `initGui(self)' function, I get an error

NameError: name `qgis` is not defined

How can fix this error?

By the way, I am trying to put the following code from this GIS.SE answer(https://gis.stackexchange.com/a/45105) into my plugin

tool = PointTool(qgis.iface.mapCanvas())
qgis.iface.mapCanvas().setMapTool(tool)

The code works fine inside QGIS main window (in Python Console), but generates the above error when moving it into the Plugin. I can't figure out how to let the PointTool respond inside a plugin. The code for PointTool class from the linked answer is:

class PointTool(QgsMapTool):   
    def __init__(self, canvas):
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas    

    def canvasPressEvent(self, event):
        pass

    ...

Best Answer

When you create a plugin, you receiv iface via the __init__ function :

def __init__(self, iface):
   self.iface = iface

After that in you code you can access to iface via self.iface.

Otherwise you can have access via qgis.utils.iface