Layer styling is one of the most complex aspects of the QGIS Python API. Once you've developed the style for a layer, it is often useful to save the styling to the QGIS Markup Language (QML) in the XML format.
You will need to download the zipped directory named saveqml
and decompress it to your qgis_data/rasters
directory from https://geospatialpython.googlecode.com/svn/saveqml.zip.
We will create a color ramp for a DEM and make it semi transparent to overlay a hillshaded tiff of the DEM. We'll save the style we create to a QML file. To do this, we need to perform the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import *
hs = QgsRasterLayer("/qgis_data/saveqml/hillshade.tif", "Hillshade") dem = QgsRasterLayer("/qgis_data/saveqml/dem.asc", "DEM")
algorithm = QgsContrastEnhancement.StretchToMinimumMaximum limits = QgsRaster.ContrastEnhancementMinMax dem.setContrastEnhancement(algorithm, limits)
s = QgsRasterShader() c = QgsColorRampShader() c.setColorRampType(QgsColorRampShader.INTERPOLATED) i = [] qri = QgsColorRampShader.ColorRampItem i.append(qri(356.334, QColor(63,159,152,255), '356.334')) i.append(qri(649.292, QColor(96,235,155,255), '649.292')) i.append(qri(942.25, QColor(100,246,174,255), '942.25')) i.append(qri(1235.21, QColor(248,251,155,255), '1235.21')) i.append(qri(1528.17, QColor(246,190,39,255), '1528.17')) i.append(qri(1821.13, QColor(242,155,39,255), '1821.13')) i.append(qri(2114.08, QColor(165,84,26,255), '2114.08')) i.append(qri(2300, QColor(236,119,83,255), '2300')) i.append(qri(2700, QColor(203,203,203,255), '2700')) c.setColorRampItemList(i) s.setRasterShaderFunction(c) ps = QgsSingleBandPseudoColorRenderer(dem.dataProvider(), 1, s) ps.setOpacity(0.5) dem.setRenderer(ps)
QgsMapLayerRegistry.instance().addMapLayers([dem, hs])
dem.saveNamedStyle("/qgis_data/saveqml/dem.qml")
The QML format is easy to read and can be edited by hand. The saveNamedStyle()
method works on vector layers in the exact same way. Instead of styling the preceding code, you can just reference the QML file using the loadNamedStyle()
method:
dem.loadNamedStyle("/qgis_data/saveqml/dem.qml")
If you save the QML file along with a shapefile and use the same filename (with the .qml
extension), then QGIS will load the style automatically when the shapefile is loaded.