Archives de catégorie : QGIS

QGIS python console-Note-before beginning…

When coding QGIS plugins, you’ll have to deal with objects such as the interface (iface object), the canvas, the layers of course. Each object has a certain number of attributes and methods. For example, layers have the attribute “source”, or “name”. They also are assigned methods like the “getSelectedFeatures” method. Notice that when applying the function “getSelectedFeatures”, you get some feature objects. Like interface, canvas and layer, features are another type of object with attributes and methods. Of course, I won’t list all the objects, attributes and methods avalaible through the QGIS API.

Another aspect is the notion of inheritance: the classes QgsVectorLayer and QgsRasterLayer are like brother objects, who have a common parent: the QgsMapLayer Class. They are both specific and contain different methods but what they have in common are the attributes and methods of their parent class: QgsMapLayer.

This API reflects a contemporary vision in programming called object oriented programming. All the programming books deal with this subject.

What I recommend you while reading the examples posts is having the API doc opened in your web navigator, so that you check the function, object properties I’m calling.

Let’s remind you the QGIS API address:
http://doc.qgis.org/
On the website, choose your version. Most of the times, it is the kore version…

QGIS-Using the python console

As previously said, the QGIS python console is a good way to test step by step your code before implementing it to your plugin…

To access the python console, just go to plugins > python console.


Notice the example instruction in the shell iface.zoomFull(): this command is applied on the interface object called iface. It performs a zoom that makes all your objects visible.
Just try typing it in the shell to see the result:

The QGIS console is similar to a python shell but there are some limitations like the impossibility of writing multiples lines of code in one time,as it is possible with the usual python shell.

Usually, the “for” and “while” statements require multiples lines. They are often used to get lists. As the “for” and “while” statements are unavalaible, you’ll have to deal with the notion of list comprehension to get a list of values.
Look at these links to learn how to use them:
http://docs.python.org/tutorial/datastructures.html
http://www.secnetix.de/olli/Python/list_comprehensions.hawk
In the examples i’ll show you in the next posts, you’ll see some examples of these notions.

You can also have to use map, filter, and reduce functions, that are used on lists:
http://docs.python.org/library/functions.html

To write functions, you’ll have to get familiar with lambda function…
http://www.secnetix.de/olli/Python/lambda_functions.hawk