Class: QgsRasterLayer

Represents a raster layer.

A QgsRasterLayer is instantiated by specifying the name of a data provider, such as “gdal” or “wms”, and a url defining the specific data set to connect to. The raster layer constructor in turn instantiates a QgsRasterDataProvider subclass corresponding to the provider type, and passes it the url. The data provider connects to the data source.

Sample usage of the QgsRasterLayer class:

my_raster_layer = QgsRasterLayer("/path/to/file.tif", "my layer")

Class Hierarchy

Inheritance diagram of qgis.core.QgsRasterLayer

Base classes

QgsMapLayer

Base class for all map layer types.

QObject

QgsAbstractProfileSource

Interface for classes which can generate elevation profiles.

Enums

LayerType

alias of RasterLayerType

Abstract Methods

clone

Returns a new instance equivalent to this one.

Methods

as_numpy

Returns the layer data as a numpy array.

attributeTable

Returns the (possibly NULL) raster attribute table for the given band bandNumber.

attributeTableCount

Returns the number of attribute tables for the raster by counting the number of bands that have an associated attribute table.

bandCount

Returns the number of bands in this layer.

bandName

Returns the name of a band given its number.

brightnessFilter

Returns the raster's brightness/contrast filter.

canCreateRasterAttributeTable

Returns True if the raster renderer is suitable for creation of a raster attribute table.

constDataProvider

Returns the source data provider.

draw

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

height

Returns the height of the (unclipped) raster.

hueSaturationFilter

Returns the raster's hue/saturation filter.

ignoreExtents

If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the data provider.

labeling

Access to labeling configuration.

labelsEnabled

Returns whether the layer contains labels which are enabled and should be drawn.

legendSymbologyItems

Returns a list with classification items (Text and color).

paletteAsPixmap

Returns a 100x100 pixmap of the color palette.

pipe

Returns the raster pipe.

previewAsImage

Draws a preview of the rasterlayer into a QImage

rasterType

Returns the 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.

renderer

Returns the raster's renderer.

resampleFilter

Returns the raster's resample filter.

resamplingStage

Returns which stage of the pipe should apply resampling.

setContrastEnhancement

Set contrast enhancement algorithm

setDataProvider

Set the data provider.

setDefaultContrastEnhancement

Sets the default contrast enhancement

setLabeling

Sets labeling configuration.

setLabelsEnabled

Sets whether labels should be enabled for the layer.

setRenderer

Sets the raster's renderer.

setResamplingStage

Select which stage of the pipe should apply resampling.

showStatusMessage

width

Returns the width of the (unclipped) raster.

writeSld

Writes the symbology of the layer into the document provided in SLD 1.0.0 format

Virtual Methods

In PyQGIS, only methods marked as virtual can be safely overridden in a Python subclass of QgsRasterLayer. See the FAQ for more details.

dataProvider

Returns the source data provider.

setSubsetString

Sets the string (typically sql) used to define a subset of the layer

subsetString

Returns the string (typically sql) used to define a subset of the layer.

Static Methods

isValidRasterFileName

This helper checks to see whether the file name appears to be a valid raster file name.

lastModified

Returns time stamp for given file name

Signals

subsetStringChanged

Emitted when the layer's subset string has changed.

Attributes

MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM

Default enhancement algorithm for multiple band raster of type different from Byte

MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM

Default enhancement algorithm for multiple band raster of type Byte

SAMPLE_SIZE

Default sample size (number of pixels) for estimated statistics/histogram calculation

SINGLE_BAND_ENHANCEMENT_ALGORITHM

Default enhancement algorithm for single band raster

class qgis.core.QgsRasterLayer[source]

Bases: QgsMapLayer, QgsAbstractProfileSource

__init__()

Constructor. Provider is not set.

__init__(uri: str | None, baseName: str | None = '', providerType: str | None = '', options: QgsRasterLayer.LayerOptions = QgsRasterLayer.LayerOptions())

This is the constructor for the RasterLayer class.

The main tasks carried out by the constructor are:

  • Load the rasters default style (.qml) file if it exists

  • Populate the RasterStatsVector with initial values for each band.

  • Calculate the layer extents

  • Determine whether the layer is gray, paletted or multiband.

  • Assign sensible defaults for the red, green, blue and gray bands.

Parameters:
  • uri (Optional[str])

  • baseName (Optional[str] = '')

  • providerType (Optional[str] = '')

  • options (QgsRasterLayer.LayerOptions = QgsRasterLayer.LayerOptions())

class LayerOptions

Bases: object

Setting options for loading raster layers.

skipCrsValidation: bool

Controls whether the layer is allowed to have an invalid/unknown CRS.

If True, then no validation will be performed on the layer’s CRS and the layer layer’s crs() may be invalid() (i.e. the layer will have no georeferencing available and will be treated as having purely numerical coordinates).

If False (the default), the layer’s CRS will be validated using QgsCoordinateReferenceSystem.validate(), which may cause a blocking, user-facing dialog asking users to manually select the correct CRS for the layer.

Added in version 3.10.

LayerType

alias of RasterLayerType

MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 1

Default enhancement algorithm for multiple band raster of type different from Byte

MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 0

Default enhancement algorithm for multiple band raster of type Byte

SAMPLE_SIZE: float = 250000.0

Default sample size (number of pixels) for estimated statistics/histogram calculation

SINGLE_BAND_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 1

Default enhancement algorithm for single band raster

as_numpy(use_masking=True, bands: List[int] | None = None) List[ndarray | MaskedArray]

Returns the layer data as a numpy array.

If use_masking is True then the returned arrays will be numpy masked arrays, masking the raster block’s nodata values.

If bands is provided, only the specified bands will be included in the returned array; otherwise, all bands will be used.

Raises:

QgsNotSupportedException – if numpy is not available on the system

Added in version 3.40.

attributeTable(self, bandNumber: int) QgsRasterAttributeTable | None[source]

Returns the (possibly NULL) raster attribute table for the given band bandNumber.

Added in version 3.30.

Parameters:

bandNumber (int)

Return type:

Optional[QgsRasterAttributeTable]

attributeTableCount(self) int[source]

Returns the number of attribute tables for the raster by counting the number of bands that have an associated attribute table.

Added in version 3.30.

Return type:

int

bandCount(self) int[source]

Returns the number of bands in this layer.

Return type:

int

bandName(self, bandNoInt: int) str[source]

Returns the name of a band given its number.

Parameters:

bandNoInt (int)

Return type:

str

brightnessFilter(self) QgsBrightnessContrastFilter | None[source]

Returns the raster’s brightness/contrast filter.

See also

resampleFilter()

Return type:

Optional[QgsBrightnessContrastFilter]

canCreateRasterAttributeTable(self) bool[source]

Returns True if the raster renderer is suitable for creation of a raster attribute table. The supported renderers are QgsPalettedRasterRenderer and QgsSingleBandPseudoColorRenderer.

Added in version 3.30.

Return type:

bool

abstract clone(self) QgsRasterLayer | None[source]

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

Return type:

Optional[QgsRasterLayer]

Returns:

a new layer instance

constDataProvider(self) QgsRasterDataProvider | None

Returns the source data provider.

This will be None if the layer is invalid.

Return type:

Optional[QgsRasterDataProvider]

virtual dataProvider(self) QgsRasterDataProvider | None[source]

Returns the source data provider.

This will be None if the layer is invalid.

Return type:

Optional[QgsRasterDataProvider]

draw(self, theQPainter: QPainter | None, myRasterViewPort: QgsRasterViewPort | None, qgsMapToPixel: QgsMapToPixel | None = None)[source]

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

Parameters:
height(self) int[source]

Returns the height of the (unclipped) raster.

See also

width()

Return type:

int

hueSaturationFilter(self) QgsHueSaturationFilter | None[source]

Returns the raster’s hue/saturation filter.

See also

resampleFilter()

Return type:

Optional[QgsHueSaturationFilter]

ignoreExtents(self) bool[source]

If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the data provider. To be used for example for WMS layers with labels or symbology that happens to be drawn outside the data extent.

Added in version 3.10.

Return type:

bool

static isValidRasterFileName(fileNameQString: str | None, retError: str | None) bool[source]

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.

Parameters:
  • fileNameQString (Optional[str])

  • retError (Optional[str])

Return type:

bool

static isValidRasterFileName(fileNameQString: str | None) bool[source]
Parameters:

fileNameQString (Optional[str])

Return type:

bool

labeling(self) QgsAbstractRasterLayerLabeling | None[source]

Access to labeling configuration. May be None if labeling is not used.

Note

Labels will only be rendered if labelsEnabled() returns True.

See also

labelsEnabled()

See also

setLabeling()

Added in version 3.42.

Return type:

Optional[QgsAbstractRasterLayerLabeling]

labelsEnabled(self) bool[source]

Returns whether the layer contains labels which are enabled and should be drawn.

Return type:

bool

Returns:

True if layer contains enabled labels

See also

labeling()

Added in version 3.42.

static lastModified(name: str | None) QDateTime[source]

Returns time stamp for given file name

Parameters:

name (Optional[str])

Return type:

QDateTime

legendSymbologyItems(self) List[Tuple[str, QColor]][source]

Returns a list with classification items (Text and color).

Deprecated since version 3.40: Use QgsRasterRenderer.createLegendNodes() instead.

Return type:

List[Tuple[str, QColor]]

paletteAsPixmap(self, bandNumber: int = 1) QPixmap[source]

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

Parameters:

bandNumber (int = 1) – the number of the band to use for generating a pixmap of the associated palette

Return type:

QPixmap

pipe(self) QgsRasterPipe | None[source]

Returns the raster pipe.

Return type:

Optional[QgsRasterPipe]

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

Draws a preview of the rasterlayer into a QImage

Parameters:
  • size (QSize)

  • bgColor (Union[QColor, Qt.GlobalColor] = Qt.white)

  • format (QImage.Format = QImage.Format_ARGB32_Premultiplied)

Return type:

QImage

rasterType(self) Qgis.RasterLayerType[source]

Returns the raster layer type (which is a read only property).

Return type:

Qgis.RasterLayerType

rasterUnitsPerPixelX(self) float[source]

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). (E.g. the value reported by the GDAL geotransform[1]).

Note

If the dataProvider() does not have native size/resolution then 1 will be returned. QgsRasterDataProvider.capabilities() can be used to test for the Qgis.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.

Return type:

float

rasterUnitsPerPixelY(self) float[source]

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).

Note

If the dataProvider() does not have native size/resolution then 1 will be returned. QgsRasterDataProvider.capabilities() can be used to test for the Qgis.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.

Return type:

float

renderer(self) QgsRasterRenderer | None[source]

Returns the raster’s renderer.

See also

setRenderer()

Return type:

Optional[QgsRasterRenderer]

resampleFilter(self) QgsRasterResampleFilter | None[source]

Returns the raster’s resample filter.

Return type:

Optional[QgsRasterResampleFilter]

resamplingStage(self) Qgis.RasterResamplingStage[source]

Returns which stage of the pipe should apply resampling.

Added in version 3.16.

Return type:

Qgis.RasterResamplingStage

setContrastEnhancement(self, algorithm: QgsContrastEnhancement.ContrastEnhancementAlgorithm, limits: Qgis.RasterRangeLimit = Qgis.RasterRangeLimit.MinimumMaximum, extent: QgsRectangle = QgsRectangle(), sampleSize: int = QgsRasterLayer.SAMPLE_SIZE, generateLookupTableFlag: bool = True)[source]

Set contrast enhancement algorithm

Parameters:
  • algorithm (QgsContrastEnhancement.ContrastEnhancementAlgorithm) – Contrast enhancement algorithm

  • limits (Qgis.RasterRangeLimit = Qgis.RasterRangeLimit.MinimumMaximum) – Limits

  • extent (QgsRectangle = QgsRectangle()) – Extent used to calculate limits, if empty, use full layer extent

  • sampleSize (int = QgsRasterLayer.SAMPLE_SIZE) – Size of data sample to calculate limits, if 0, use full resolution

  • generateLookupTableFlag (bool = True) – Generate lookup table.

setDataProvider(self, provider: str | None)[source]

Set the data provider.

Deprecated since version 3.40: Use the version with ProviderOptions instead.

Parameters:

provider (Optional[str])

setDataProvider(self, provider: str | None, options: QgsDataProvider.ProviderOptions, flags: Qgis.DataProviderReadFlags | Qgis.DataProviderReadFlag = Qgis.DataProviderReadFlags())[source]

Set the data provider.

Parameters:

Added in version 3.2.

setDefaultContrastEnhancement(self)[source]

Sets the default contrast enhancement

setLabeling(self, labeling: QgsAbstractRasterLayerLabeling | None)[source]

Sets labeling configuration. Takes ownership of the object.

See also

labeling()

Added in version 3.42.

Parameters:

labeling (Optional[QgsAbstractRasterLayerLabeling])

setLabelsEnabled(self, enabled: bool)[source]

Sets whether labels should be enabled for the layer.

Note

Labels will only be rendered if labelsEnabled() is True and a labeling object is returned by labeling().

See also

labelsEnabled()

See also

labeling()

Added in version 3.42.

Parameters:

enabled (bool)

setRenderer(self, renderer: QgsRasterRenderer | None)[source]

Sets the raster’s renderer. Takes ownership of the renderer object.

See also

renderer()

Parameters:

renderer (Optional[QgsRasterRenderer])

setResamplingStage(self, stage: Qgis.RasterResamplingStage)[source]

Select which stage of the pipe should apply resampling.

Added in version 3.16.

Parameters:

stage (Qgis.RasterResamplingStage)

virtual setSubsetString(self, subset: str | None) bool[source]

Sets the string (typically sql) used to define a subset of the layer

Parameters:

subset (Optional[str]) – The subset string. This may be the where clause of a sql statement or other definition string specific to the underlying dataprovider and data store.

Return type:

bool

Returns:

True, when setting the subset string was successful, False otherwise

Added in version 3.12.

showStatusMessage(self, message: str | None)[source]
Parameters:

message (Optional[str])

virtual subsetString(self) str[source]

Returns the string (typically sql) used to define a subset of the layer.

Return type:

str

Returns:

The subset string or an empty string if not implemented by the provider

Added in version 3.12.

signal subsetStringChanged[source]

Emitted when the layer’s subset string has changed.

Added in version 3.12.

width(self) int[source]

Returns the width of the (unclipped) raster.

See also

height()

Return type:

int

writeSld(self, node: QDomNode, doc: QDomDocument, errorMessage: str | None, props: Dict[str, Any] = {}) bool[source]

Writes the symbology of the layer into the document provided in SLD 1.0.0 format

Parameters:
  • node (QDomNode) – the node that will have the style element added to it.

  • doc (QDomDocument) – the document that will have the QDomNode added.

  • errorMessage (Optional[str]) – reference to string that will be updated with any error messages

  • props (Dict[str, Any] = {}) – a open ended set of properties that can drive/inform the SLD encoding

Return type:

bool

Returns:

True in case of success

Deprecated since version 3.44: Use the version with QgsSldExportContext instead.

writeSld(self, node: QDomNode, doc: QDomDocument, context: QgsSldExportContext) bool[source]

Writes the symbology of the layer into the document provided in SLD 1.1 format

Parameters:
  • node (QDomNode) – the node that will have the style element added to it.

  • doc (QDomDocument) – the document that will have the QDomNode added.

  • context (QgsSldExportContext) – export context. Errors and warnings may be retrieved from this context.

Return type:

bool

Returns:

True in case of success

Added in version 3.44.