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.
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.
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:
QtGui
library in order to access the QColor
object that is used to describe colors in the PyQGIS API:from PyQt4.QtGui import *
lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(lyr)
symbols = lyr.rendererV2().symbols()
sym = symbols[0]
sym.setColor(QColor.fromRgb(255,0,0))
lyr.triggerRepaint()
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.