My first QGIS python script

When I searched the internet for the title of this post all I found were links to plugin tutorials… Not exactly what you need when you want to get started with python SCRIPTING in QGIS.

Here’s how to start.

First install QGIS version 2.0 or higher.

Open the python console by clicking “plugins/python console”

When the console launches it adds the QGIS core modules straight off the bat making those functions immediately available to the console. You can start importing shape files or creating layers directly in the console command line right now. Try copying the following at the console >>> prompt

bbox_min_lon=0
bbox_min_lat=0
bbox_max_lon=10
bbox_max_lat=10
bboxlayer=QgsVectorLayer("Polygon?crs=epsg:4326&field=id:integer&field=name:string(20)&index=yes","bbox_polygon","memory")
bbl_dp = bboxlayer.dataProvider()
bboxlayer.startEditing()
bbox_feature = QgsFeature()
bbox_feature.setGeometry(QgsGeometry.fromPolygon( [ [ \
QgsPoint(bbox_min_lon,bbox_min_lat),\
QgsPoint(bbox_min_lon,bbox_max_lat), \
QgsPoint(bbox_max_lon,bbox_max_lat),
QgsPoint(bbox_max_lon,bbox_min_lat) ] ] ))
(res, outFeats) = bboxlayer.dataProvider().addFeatures([bbox_feature])
bboxlayer.commitChanges()
QgsMapLayerRegistry.instance().addMapLayer(bboxlayer)

yay you made a simple polygon in WGS84 from scratch

Now if you want to put code in a script you can open the script editor from the python console. Its the button that looks like a pencil and paper.

Now you can paste the example code directly in here then hit the blue triangle to run it.

Look you made anothe layer with a single polygon in it hooray.

Now that you’re started you need to head over to http://docs.qgis.org/2.2/en/docs/pyqgis_developer_cookbook/index.html

It’s great. Feel free to come back here to copy and paste from my examples.

Leave a Reply

Your email address will not be published. Required fields are marked *


seven × 9 =