Symbolizing a vector layer

The appearance of the layers on a QGIS map is controlled by its symbology. A layer's symbology includes the renderer and one or more symbols. The renderer provides rules dictating the appearance of symbols. The symbols describe properties, including color, shape, size, and linewidth. In this recipe, we'll load a vector layer, change its symbology, and refresh the map.

Getting ready

Download the following zipped shapefile and extract it to your qgis_data directory into a folder named ms from https://geospatialpython.googlecode.com/files/Mississippi.zip.

How to do it...

We will load a layer, add it to the map layer registry, change the layer's color, and then refresh the map. To do this, perform the following steps:

  1. First, using the QGIS Python Console, we must import the QtGui library in order to access the QColor object that is used to describe colors in the PyQGIS API:
    from PyQt4.QtGui import *
    
  2. Next, we create our vector layer, as follows:
    lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
    
  3. Then, we add it to the map layer registry:
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    
  4. Now, we access the layer's symbol list through the layer's renderer object:
    symbols = lyr.rendererV2().symbols()
    
  5. Next, we reference the first symbol, which in this case is the only symbol:
    sym = symbols[0]
    
  6. Once we have the symbol, we can set its color:
    sym.setColor(QColor.fromRgb(255,0,0))
    
  7. We must remember to repaint the layer in order to force the update:
    lyr.triggerRepaint()
    

How it works...

Changing the color of a layer sounds simple, but remember that in QGIS, anything you see must be altered through the canvas API. Therefore, we add the layer to the map and access the layer's symbology through its renderer. The map canvas is rendered as a raster image. The renderer is responsible for turning the layer data into a bitmap image, so the presentation information for a layer is stored with its renderer.

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

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