Accessing the map canvas

Maps in QGIS are controlled through the map canvas. In this recipe, we'll access the canvas and then check one of its properties to ensure that we have control over the object.

Getting ready

The only thing you need to do for this recipe is to open QGIS and select Python Console from the Plugins menu.

How to do it...

We will assign the map canvas to a variable named canvas. Then, we'll check the size property of the canvas to get its size in pixels. To do this, perform the following steps:

  1. Enter the following line in the QGIS Python Console:
    canvas = qgis.utils.iface.mapCanvas()
    
  2. Now, to ensure that we have properly accessed the canvas, check its size in pixels using the following line of code:
    canvas.size()
    
  3. Verify that QGIS returns a QSize object that contains the canvas's pixel size, similar to the following format:
    PyQt4.QtCore.QSize(698, 138)
    

How it works...

Everything in QGIS centers on the canvas. The canvas is part of the QGIS interface or iface API. Anything you see on the screen when using QGIS is generated through the iface API. Note that the iface object is only available to scripts and plugins. When you are building a standalone application, you must initialize your own QgsMapCanvas object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset