[GIS] Global name canvas is not defined

pyqgisqgis-2qgis-plugins

I am just trying to print the layer name using python in my QGIS plugin by following code.

allLayers = canvas.layers()
for i in allLayers: print i.name()

It is saying an error: Global name canvas is not defined. How to fix this?

Best Answer

You are calling the wrong class. What you need to call is mapCanvas, and not canvas.

Change your code to this:

allLayers = iface.mapCanvas().layers()
for i in allLayers:
    print i.name()

This will print all of your current layers' names.

Also note that you need to indent the print line. I assume in your post this was just a copy/paste problem, but if not, go ahead and change it, or it will not work :-)