Subgroup: Raster

Class: QgsRasterLayer

class qgis.core.QgsRasterLayer

Bases: qgis._core.QgsMapLayer

This class provides qgis with the ability to render raster datasets onto the mapcanvas.

The qgsrasterlayer class makes use of gdal for data io, and thus supports any gdal supported format. The constructor attempts to infer what type of file (LayerType) is being opened - not in terms of the file format (tif, ascii grid etc.) but rather in terms of whether the image is a GRAYSCALE, PaletteD or Multiband,

Within the three allowable raster layer types, there are 8 permutations of how a layer can actually be rendered. These are defined in the DrawingStyle enum and consist of:

SingleBandGray -> a GRAYSCALE layer drawn as a range of gray colors (0-255) SingleBandPseudoColor -> a GRAYSCALE layer drawn using a pseudocolor algorithm PalettedSingleBandGray -> a PaletteD layer drawn in gray scale (using only one of the color components) PalettedSingleBandPseudoColor -> a PaletteD layer having only one of its color components rendered as pseudo color PalettedMultiBandColor -> a PaletteD image where the bands contains 24bit color info and 8 bits is pulled out per color MultiBandSingleBandGray -> a layer containing 2 or more bands, but using only one band to produce a grayscale image MultiBandSingleBandPseudoColor -> a layer containing 2 or more bands, but using only one band to produce a pseudocolor image MultiBandColor -> a layer containing 2 or more bands, mapped to the three RGBcolors. In the case of a multiband with only two bands, one band will have to be mapped to more than one color

Each of the above mentioned drawing styles is implemented in its own draw* function. Some of the drawing styles listed above require statistics about the layer such as the min / max / mean / stddev etc. statistics for a band can be gathered using the bandStatistics function. Note that statistics gathering is a slow process and every effort should be made to call this function as few times as possible. For this reason, qgsraster has a vector class member to store stats for each band. The constructor initializes this vector on startup, but only populates the band name and number fields.

Note that where bands are of gdal ‘undefined’ type, their values may exceed the renderable range of 0-255. Because of this a linear scaling histogram enhanceContrast is applied to undefined layers to normalise the data into the 0-255 range.

A qgsrasterlayer band can be referred to either by name or by number (base=1). It should be noted that band names as stored in datafiles may not be unique, and so the rasterlayer class appends the band number in brackets behind each band name.

Sample usage of the QgsRasterLayer class:

In order to automate redrawing of a raster layer, you should like it to a map canvas like this :

Once a layer has been created you can find out what type of layer it is (GrayOrUndefined, Palette or Multiband):

Raster layers can also have an arbitrary level of transparency defined, and have their color palettes inverted using the setTransparency and setInvertHistogram methods.

Pseudocolor images can have their output adjusted to a given number of standard deviations using the setStandardDeviations method.

The final area of functionality you may be interested in is band mapping. Band mapping allows you to choose arbitrary band -> color mappings and is applicable only to Palette and Multiband rasters, There are four mappings that can be made: red, green, blue and gray. Mappings are non-exclusive. That is a given band can be assigned to no, some or all color mappings. The constructor sets sensible defaults for band mappings but these can be overridden at run time using the setRedBandName, setGreenBandName, setBlueBandName and setGrayBandName methods.

Methods

abstract Returns the abstract of the layer used by QGIS Server in GetCapabilities request.
appendError
attribution Returns the attribution of the layer used by QGIS Server in GetCapabilities request.
attributionUrl Returns the attribution URL of the layer used by QGIS Server in GetCapabilities request.
autoRefreshInterval Returns the auto refresh interval (in milliseconds).
bandCount Get the number of bands in this layer
bandName Get the name of a band given its number
blendMode Returns the current blending mode for a layer.
blockSignals
brightnessFilter
childEvent
children
clone Returns a new instance equivalent to this one.
connectNotify
constDataProvider Returns the data provider in a const-correct manner
createMapRenderer Return new instance of QgsMapLayerRenderer that will be used for rendering of given context
crs Returns the layer’s spatial reference system.
customEvent
customProperty Read a custom property from layer.
customPropertyKeys Returns list of all keys within custom properties.
dataProvider
dataUrl Returns the DataUrl of the layer used by QGIS Server in GetCapabilities request.
dataUrlFormat Returns the DataUrl format of the layer used by QGIS Server in GetCapabilities request.
deleteLater
dependencies Gets the list of dependencies.
disconnect
disconnectNotify
draw This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap
dumpObjectInfo
dumpObjectTree
dynamicPropertyNames
emitStyleChanged Triggers an emission of the styleChanged() signal.
error Get current status error.
event
eventFilter
exportNamedMetadata Export the current metadata of this layer as named metadata in a QDomDocument
exportNamedStyle Export the properties of this layer as named style in a QDomDocument
exportSldStyle Export the properties of this layer as SLD style in a QDomDocument
extensionPropertyType Returns the extension of a Property.
extent Returns the extent of the layer.
findChild findChild(self, Tuple, name: str = ‘’, options: Union[Qt.FindChildOptions, Qt.FindChildOption] = Qt.FindChildrenRecursively) -> QObject
findChildren findChildren(self, Tuple, name: str = ‘’, options: Union[Qt.FindChildOptions, Qt.FindChildOption] = Qt.FindChildrenRecursively) -> List[QObject]
formatLayerName A convenience function to capitalize and format a layer name.
hasAutoRefreshEnabled Returns true if auto refresh is enabled for the layer.
hasDependencyCycle
hasScaleBasedVisibility Returns whether scale based visibility is enabled for the layer.
height Accessor that returns the height of the (unclipped) raster
htmlMetadata
hueSaturationFilter
id Returns the layer’s unique ID, which is used to access this layer from QgsProject.
importNamedMetadata Import the metadata of this layer from a QDomDocument
importNamedStyle Import the properties of this layer from a QDomDocument
inherits
installEventFilter
isEditable Returns true if the layer can be edited.
isInScaleRange Tests whether the layer should be visible at the specified scale.
isRefreshOnNotifyEnabled Returns true if the refresh on provider nofification is enabled
isSignalConnected
isSpatial
isValid Return the status of the layer.
isValidRasterFileName This helper checks to see whether the file name appears to be a valid raster file name.
isWidgetType
isWindowType
keywordList Returns the keyword list of the layer used by QGIS Server in GetCapabilities request.
killTimer
lastModified Return time stamp for given file name
legend Can be null.
legendSymbologyItems Returns a list with classification items (Text and color)
legendUrl Returns the URL for the layer’s legend.
legendUrlFormat Returns the format for a URL based layer legend.
loadDefaultMetadata Retrieve the default metadata for this layer if one
loadDefaultStyle Retrieve the default style for this layer if one
loadNamedMetadata Retrieve a named metadata for this layer if one
loadNamedMetadataFromDatabase Retrieve a named metadata for this layer from a sqlite database.
loadNamedStyle Retrieve a named style for this layer if one
loadNamedStyleFromDatabase Retrieve a named style for this layer from a sqlite database.
loadSldStyle Attempts to style the layer using the formatting from an SLD type file.
maximumScale Returns the maximum map scale (i.e.
metaObject
metadata Returns a reference to the layer’s metadata store.
metadataUri Retrieve the metadata URI for this layer
metadataUrl Returns the metadata URL of the layer used by QGIS Server in GetCapabilities request.
metadataUrlFormat Returns the metadata format of the layer used by QGIS Server in GetCapabilities request.
metadataUrlType Returns the metadata type of the layer used by QGIS Server in GetCapabilities request.
minimumScale Returns the minimum map scale (i.e.
moveToThread
name Returns the display name of the layer.
objectName
paletteAsPixmap Get an 100x100 pixmap of the color palette.
parent
pipe Get raster pipe
previewAsImage Draws a preview of the rasterlayer into a QImage
property
providerType [ data provider interface ] Which provider is being used for this Raster Layer?
publicSource Gets a version of the internal layer definition that has sensitive bits removed (for example, the password).
pyqtConfigure Each keyword argument is either the name of a Qt property or a Qt signal.
rasterType Accessor for raster layer type (which is a read only property)
rasterUnitsPerPixelX Returns the number of raster units per each raster pixel in X axis.
rasterUnitsPerPixelY Returns the number of raster units per each raster pixel in Y axis.
readCommonStyle
readCustomProperties
readLayerXml Sets state from Dom document
readOnly Returns if this layer is read only.
readSld
readStyle Read the style information for the current layer from the Dom node supplied
readStyleManager
readSymbology Read the symbology for the current layer from the Dom node supplied
readXml Reads layer specific state from project file Dom node
receivers
refreshOnNotifyMessage Returns the message that should be notified by the provider to triggerRepaint
reload Synchronises with changes in the datasource
removeCustomProperty Remove a custom property from layer.
removeEventFilter
renderer
renderer3D Returns 3D renderer associated with the layer.
resampleFilter Set raster resample filter.
resolveReferences Resolve references to other layers (kept as layer IDs after reading XML) into layer objects.
saveDefaultMetadata Save the current metadata of this layer as the default metadata
saveDefaultStyle Save the properties of this layer as the default style
saveNamedMetadata Save the current metadata of this layer as a named metadata
saveNamedStyle Save the properties of this layer as a named style
saveSldStyle Saves the properties of this layer to an SLD format file.
sender
senderSignalIndex
setAbstract Sets the abstract of the layer used by QGIS Server in GetCapabilities request.
setAttribution Sets the attribution of the layer used by QGIS Server in GetCapabilities request.
setAttributionUrl Sets the attribution URL of the layer used by QGIS Server in GetCapabilities request.
setAutoRefreshEnabled Sets whether auto refresh is enabled for the layer.
setAutoRefreshInterval Sets the auto refresh interval (in milliseconds) for the layer.
setBlendMode Set the blending mode used for rendering a layer.
setContrastEnhancement Set contrast enhancement algorithm
setCrs Sets layer’s spatial reference system
setCustomProperties Set custom properties for layer.
setCustomProperty Set a custom property for layer.
setDataProvider [ data provider interface ] Set the data provider
setDataUrl Sets the DataUrl of the layer used by QGIS Server in GetCapabilities request.
setDataUrlFormat Sets the DataUrl format of the layer used by QGIS Server in GetCapabilities request.
setDefaultContrastEnhancement Set default contrast enhancement
setDependencies Sets the list of dependencies.
setError
setExtent
setKeywordList Sets the keyword list of the layer used by QGIS Server in GetCapabilities request.
setLayerOrder Reorders the previously selected sublayers of this layer from bottom to top
setLegend Assign a legend controller to the map layer.
setLegendUrl Sets the URL for the layer’s legend.
setLegendUrlFormat Sets the format for a URL based layer legend.
setMaximumScale Sets the maximum map scale (i.e.
setMetadata Sets the layer’s metadata store.
setMetadataUrl Sets the metadata URL of the layer used by QGIS Server in GetCapabilities request.
setMetadataUrlFormat Sets the metadata format of the layer used by QGIS Server in GetCapabilities request.
setMetadataUrlType Set the metadata type of the layer used by QGIS Server in GetCapabilities request MetadataUrlType indicates the standard to which the metadata complies.
setMinimumScale Sets the minimum map scale (i.e.
setName Set the display name of the layer.
setObjectName
setParent
setProperty
setRefreshOnNofifyMessage Set the notification message that triggers repaine
setRefreshOnNotifyEnabled Set whether provider notification is connected to triggerRepaint
setRenderer Set raster renderer.
setRenderer3D Sets 3D renderer for the layer.
setScaleBasedVisibility Sets whether scale based visibility is enabled for the layer.
setShortName Sets the short name of the layer used by QGIS Server to identify the layer.
setSubLayerVisibility Set the visibility of the given sublayer name
setTitle Sets the title of the layer used by QGIS Server in GetCapabilities request.
setValid
shortName Returns the short name of the layer used by QGIS Server to identify the layer.
showStatusMessage
signalsBlocked
source Returns the source for the layer.
startTimer
styleManager Get access to the layer’s style manager.
styleURI Retrieve the style URI for this layer
subLayers Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS
thread
timerEvent
timestamp Time stamp of data source in the moment when data/metadata were loaded by provider
title Returns the title of the layer used by QGIS Server in GetCapabilities request.
tr
triggerRepaint Will advise the map canvas (and any other interested party) that this layer requires to be repainted.
type Returns the type of the layer.
undoStack Return pointer to layer’s undo stack
undoStackStyles Return pointer to layer’s style undo stack
width Accessor that returns the width of the (unclipped) raster
writeCommonStyle
writeCustomProperties
writeLayerXml Stores state in Dom node
writeStyle Write the style for the layer into the docment provided
writeStyleManager
writeSymbology Write the symbology for the layer into the docment provided
writeXml Write layer specific state to project file Dom node

Attributes

ColorLayer
ColorRampShader
FreakOutShader
GrayOrUndefined
MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM
MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS
MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM
MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS
Metadata
Multiband
Palette
PluginLayer
PseudoColorShader
RasterLayer
SAMPLE_SIZE
SINGLE_BAND_ENHANCEMENT_ALGORITHM
SINGLE_BAND_MIN_MAX_LIMITS
Style
UndefinedShader
UserDefinedShader
VectorLayer
autoRefreshIntervalChanged Emitted when the auto refresh interval changes.
blendModeChanged Signal emitted when the blend mode is changed, through QgsMapLayer.setBlendMode() [signal]
configChanged Emitted whenever the configuration is changed.
crsChanged Emit a signal that layer’s CRS has been reset [signal]
dataChanged Data of layer changed [signal]
dependenciesChanged Emitted when dependencies are changed.
destroyed destroyed(self, QObject = None) [signal]
legendChanged Signal emitted when legend of the layer has changed
metadataChanged Emitted when the layer’s metadata is changed.
nameChanged Emitted when the name has been changed
objectNameChanged objectNameChanged(self, str) [signal]
recalculateExtents This is used to send a request that any mapcanvas using this layer update its extents [signal]
renderer3DChanged Signal emitted when 3D renderer associated with the layer has changed.
rendererChanged Signal emitted when renderer is changed.
repaintRequested By emitting this signal the layer tells that either appearance or content have been changed and any view showing the rendered layer should refresh itself.
staticMetaObject
statusChanged Emit a signal with status (e.g.
styleChanged Signal emitted whenever a change affects the layer’s style.
willBeDeleted Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid state: the last chance for other pieces of code for some cleanup if they use the layer.
ColorLayer = 3
ColorRampShader = 3
class ColorShadingAlgorithm

Bases: int

FreakOutShader = 2
GrayOrUndefined = 0
class LayerOptions(loadDefaultStyle: bool = True)

Bases: sip.wrapper

Constructor for LayerOptions.

QgsRasterLayer.LayerOptions(QgsRasterLayer.LayerOptions)

loadDefaultStyle
class LayerType

Bases: int

MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM = 1
MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS = 3
MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM = 0
MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS = 1
Multiband = 2
Palette = 1
PseudoColorShader = 1
SAMPLE_SIZE = 250000.0
SINGLE_BAND_ENHANCEMENT_ALGORITHM = 1
SINGLE_BAND_MIN_MAX_LIMITS = 1
UndefinedShader = 0
UserDefinedShader = 4
appendError()
bandCount(self) → int

Get the number of bands in this layer

bandName(self, bandNoInt: int) → str

Get the name of a band given its number

brightnessFilter(self) → QgsBrightnessContrastFilter
childEvent()
clone(self) → QgsRasterLayer

Returns a new instance equivalent to this one. A new provider is created for the same data source and renderer is cloned too.

Returns:a new layer instance

New in version 3.0.

connectNotify()
constDataProvider(self) → QgsRasterDataProvider

Returns the data provider in a const-correct manner

Note

available in Python bindings as constDataProvider()

createMapRenderer(self, rendererContext: QgsRenderContext) → QgsMapLayerRenderer

Return new instance of QgsMapLayerRenderer that will be used for rendering of given context

New in version 2.4.

customEvent()
dataProvider(self) → QgsRasterDataProvider
disconnectNotify()
draw(self, theQPainter: QPainter, myRasterViewPort: QgsRasterViewPort, qgsMapToPixel: QgsMapToPixel = None)

This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap

hasDependencyCycle()
height(self) → int

Accessor that returns the height of the (unclipped) raster

htmlMetadata(self) → str
hueSaturationFilter(self) → QgsHueSaturationFilter
isSignalConnected()
isSpatial(self) → bool
isValidRasterFileName(fileNameQString: str, retError: str) → bool

This helper checks to see whether the file name appears to be a valid raster file name. If the file name looks like it could be valid, but some sort of error occurs in processing the file, the error is returned in retError.

isValidRasterFileName(fileNameQString: str) -> bool

lastModified(name: str) → QDateTime

Return time stamp for given file name

legendSymbologyItems(self) → object

Returns a list with classification items (Text and color)

paletteAsPixmap(self, bandNumber: int = 1) → QPixmap

Get an 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned

pipe(self) → QgsRasterPipe

Get raster pipe

previewAsImage(self, size: QSize, bgColor: Union[QColor, Qt.GlobalColor] = Qt.white, format: QImage.Format = QImage.Format_ARGB32_Premultiplied) → QImage

Draws a preview of the rasterlayer into a QImage

New in version 2.4.

providerType(self) → str

[ data provider interface ] Which provider is being used for this Raster Layer?

rasterType(self) → QgsRasterLayer.LayerType

Accessor for raster layer type (which is a read only property)

rasterUnitsPerPixelX(self) → float

Returns the number of raster units per each raster pixel in X axis. In a world file, this is normally the first row (without the sign)

rasterUnitsPerPixelY(self) → float

Returns the number of raster units per each raster pixel in Y axis. In a world file, this is normally the first row (without the sign)

readCommonStyle()
readCustomProperties()
readStyle(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext) → bool

Read the style information for the current layer from the Dom node supplied

readStyleManager()
readSymbology(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext) → bool

Read the symbology for the current layer from the Dom node supplied

readXml(self, layer_node: QDomNode, context: QgsReadWriteContext) → bool

Reads layer specific state from project file Dom node

receivers()
reload(self)

Synchronises with changes in the datasource

renderer(self) → QgsRasterRenderer
resampleFilter(self) → QgsRasterResampleFilter

Set raster resample filter. Takes ownership of the resample filter object

sender()
senderSignalIndex()
setContrastEnhancement(self, algorithm: QgsContrastEnhancement.ContrastEnhancementAlgorithm, limits: QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax, extent: QgsRectangle = QgsRectangle(), sampleSize: int = QgsRasterLayer.SAMPLE_SIZE, generateLookupTableFlag: bool = True)

Set contrast enhancement algorithm

Parameters:
  • algorithm – Contrast enhancement algorithm
  • limits – Limits
  • extent – Extent used to calculate limits, if empty, use full layer extent
  • sampleSize – Size of data sample to calculate limits, if 0, use full resolution
  • generateLookupTableFlag – Generate lookup table. *
setDataProvider(self, provider: str)

[ data provider interface ] Set the data provider

setDefaultContrastEnhancement(self)

Set default contrast enhancement

setError()
setExtent()
setLayerOrder(self, layers: Iterable[str])

Reorders the previously selected sublayers of this layer from bottom to top

(Useful for providers that manage their own layers, such as WMS)

setRenderer(self, renderer: QgsRasterRenderer)

Set raster renderer. Takes ownership of the renderer object

setSubLayerVisibility(self, name: str, vis: bool)

Set the visibility of the given sublayer name

setValid()
showStatusMessage(self, message: str)
subLayers(self) → List[str]

Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS

timerEvent()
timestamp(self) → QDateTime

Time stamp of data source in the moment when data/metadata were loaded by provider

width(self) → int

Accessor that returns the width of the (unclipped) raster

writeCommonStyle()
writeCustomProperties()
writeStyle(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext) → bool

Write the style for the layer into the docment provided

writeStyleManager()
writeSymbology(self, a0: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext) → bool

Write the symbology for the layer into the docment provided

writeXml(self, layer_node: QDomNode, doc: QDomDocument, context: QgsReadWriteContext) → bool

Write layer specific state to project file Dom node