PyQGIS like a Boss

Mittwoch, 31. Oktober 2012

So you want to use a custom symbology for your layers and achieve that through Python.

Let me tell you first: The easy way is the WRONG way!
Because QGIScrashes with a "Win32RuntimeException" if you try the easy way.
So DON'T GO THERE and brace yourself for a detour!

Instead of creating a new Symbol, which contains all the fancy SymbologyLayers with your amazing Arrowheads for PolyLines and whatnot, you create just your beautiful SymbologyLayers and add it to the pre-existing Symbol.

This example shows a function which you can use to set a symbologystyle for a PolyLine-Layer with two styles to choose from: Awesome Arrowheads for your lines, or ugly dots.

But everytime you do that QGIS punches you in the face with a prompt to select the coordinate-reference-system you want for the new layer.

To get rid of all that you need tell QGIS that you don't want that...easy right.

First you create a settings-variable. And because QGIS ist awesome you just use the PyQt4-Class QSettings. Then you set the value of "/Projections/defaultBehaviour" to whatever you need.
There are three possibilities:

LineString is the type of layer you want to create. (e.g. Point, LineString or Polygon)name is obviously the displayed name of the layer.memory is the storagetype. it is just an unsaved memorylayer in this example.

After that you need to specifiy the layerattributes. (if you want to)
To do that you have to get the dataprovider of the layer and set it to "editable" to add the attributes you want the included features to have. To commit your changes to the attributetable use the commitChanges()-Function of the QgsVectorLayer.