Class: QgsRasterLayer

class qgis.core.QgsRasterLayer

Bases: QgsMapLayer, QgsAbstractProfileSource

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

QgsRasterLayer() Constructor. Provider is not set.

QgsRasterLayer(uri: Optional[str], baseName: Optional[str] = ‘’, providerType: Optional[str] = ‘’, 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.

Enums

LayerType

alias of RasterLayerType

Methods

accept

param visitor:

appendError

Add error message

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.

childEvent

clone

Returns a new instance equivalent to this one.

connectNotify

constDataProvider

Returns the source data provider.

createMapRenderer

param rendererContext:

createProfileGenerator

param request:

customEvent

dataProvider

Returns the source data provider.

decodedSource

param source:

disconnectNotify

draw

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

elevationProperties

rtype:

Optional[QgsMapLayerElevationProperties]

encodedSource

param source:

hasDependencyCycle

Checks whether a new set of dependencies will introduce a cycle this method is now deprecated and always return False, because circular dependencies are now correctly managed.

height

Returns the height of the (unclipped) raster.

htmlMetadata

rtype:

str

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.

invalidateWgs84Extent

Invalidates the WGS84 extent.

isSignalConnected

isSpatial

rtype:

bool

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

legendSymbologyItems

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

opacity

rtype:

float

paletteAsPixmap

Returns a 100x100 pixmap of the color palette.

pipe

Returns the raster pipe.

previewAsImage

Draws a preview of the rasterlayer into a QImage

properties

rtype:

Qgis.MapLayerProperties

providerType

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

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.

readCommonStyle

Read style data common to all layer types

readCustomProperties

Read custom properties from project file.

readStyle

param node:

readStyleManager

Read style manager's configuration (if any).

readSymbology

param node:

readXml

param layer_node:

receivers

reload

renderer

Returns the raster's renderer.

resampleFilter

Returns the raster's resample filter.

resamplingStage

Returns which stage of the pipe should apply resampling.

sender

senderSignalIndex

setContrastEnhancement

Set contrast enhancement algorithm

setDataProvider

Set the data provider.

setDefaultContrastEnhancement

Sets the default contrast enhancement

setError

Sets error message

setExtent

Sets the extent

setExtent3D

Sets the extent

setLayerOrder

param layers:

setOpacity

param opacity:

setProviderType

Sets the providerType (provider key)

setRenderer

Sets the raster's renderer.

setResamplingStage

Select which stage of the pipe should apply resampling.

setSubLayerVisibility

param name:

setSubsetString

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

setTransformContext

Sets the coordinate transform context to transformContext

setValid

Sets whether layer is valid or not

showStatusMessage

param message:

subLayers

rtype:

List[str]

subsetString

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

temporalProperties

rtype:

Optional[QgsMapLayerTemporalProperties]

timerEvent

timestamp

rtype:

QDateTime

width

Returns the width of the (unclipped) raster.

writeCommonStyle

Write style data common to all layer types

writeCustomProperties

Write custom properties to project file.

writeSld

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

writeStyle

param node:

writeStyleManager

Write style manager's configuration (if exists).

writeSymbology

param a0:

writeXml

param layer_node:

Signals

subsetStringChanged

pyqtSignal(*types, name: str = ..., revision: int = ..., arguments: Sequence = ...) -> PYQT_SIGNAL

Attributes

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

SAMPLE_SIZE

SINGLE_BAND_ENHANCEMENT_ALGORITHM

SINGLE_BAND_MIN_MAX_LIMITS

class LayerOptions(loadDefaultStyle: bool = True, transformContext: QgsCoordinateTransformContext = QgsCoordinateTransformContext())

Bases: sip.wrapper

Constructor for LayerOptions.

QgsRasterLayer.LayerOptions(a0: QgsRasterLayer.LayerOptions)

loadDefaultStyle
skipCrsValidation
transformContext
LayerType

alias of RasterLayerType

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
SAMPLE_SIZE = 250000.0
SINGLE_BAND_ENHANCEMENT_ALGORITHM = 1
SINGLE_BAND_MIN_MAX_LIMITS = 1
accept(self, visitor: QgsStyleEntityVisitorInterface | None) bool
Parameters:

visitor (Optional[QgsStyleEntityVisitorInterface])

Return type:

bool

appendError(self, error: QgsErrorMessage)

Add error message

attributeTable(self, bandNumber: int) QgsRasterAttributeTable | None

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

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

Returns the number of bands in this layer.

Return type:

int

bandName(self, bandNoInt: int) str

Returns the name of a band given its number.

Parameters:

bandNoInt (int)

Return type:

str

brightnessFilter(self) QgsBrightnessContrastFilter | None

Returns the raster’s brightness/contrast filter.

See also

resampleFilter()

Return type:

Optional[QgsBrightnessContrastFilter]

canCreateRasterAttributeTable(self) bool

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

childEvent(self, a0: QChildEvent | None)
clone(self) QgsRasterLayer | None

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

connectNotify(self, signal: QMetaMethod)
constDataProvider(self) QgsRasterDataProvider | None

Returns the source data provider.

This will be None if the layer is invalid.

Return type:

Optional[QgsRasterDataProvider]

createMapRenderer(self, rendererContext: QgsRenderContext) QgsMapLayerRenderer | None
Parameters:

rendererContext (QgsRenderContext)

Return type:

Optional[QgsMapLayerRenderer]

createProfileGenerator(self, request: QgsProfileRequest) QgsAbstractProfileGenerator | None
Parameters:

request (QgsProfileRequest)

Return type:

Optional[QgsAbstractProfileGenerator]

customEvent(self, a0: QEvent | None)
dataProvider(self) QgsRasterDataProvider | None

Returns the source data provider.

This will be None if the layer is invalid.

Return type:

Optional[QgsRasterDataProvider]

decodedSource(self, source: str | None, provider: str | None, context: QgsReadWriteContext) str
Parameters:
Return type:

str

disconnectNotify(self, signal: QMetaMethod)
draw(self, theQPainter: QPainter | None, myRasterViewPort: QgsRasterViewPort | None, qgsMapToPixel: QgsMapToPixel | None = None)

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

Parameters:
elevationProperties(self) QgsMapLayerElevationProperties | None
Return type:

Optional[QgsMapLayerElevationProperties]

encodedSource(self, source: str | None, context: QgsReadWriteContext) str
Parameters:
Return type:

str

hasDependencyCycle(self, a0: Iterable[QgsMapLayerDependency]) bool

Checks whether a new set of dependencies will introduce a cycle this method is now deprecated and always return False, because circular dependencies are now correctly managed.

Deprecated since version QGIS: 3.10

height(self) int

Returns the height of the (unclipped) raster.

See also

width()

Return type:

int

htmlMetadata(self) str
Return type:

str

hueSaturationFilter(self) QgsHueSaturationFilter | None

Returns the raster’s hue/saturation filter.

See also

resampleFilter()

Return type:

Optional[QgsHueSaturationFilter]

ignoreExtents(self) bool

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

invalidateWgs84Extent(self)

Invalidates the WGS84 extent. If FlagTrustLayerMetadata is enabled, the extent is not invalidated because we want to trust metadata whatever happens.

Added in version 3.20.

isSignalConnected(self, signal: QMetaMethod) bool
isSpatial(self) bool
Return type:

bool

isValidRasterFileName(fileNameQString: str | None, retError: str | None) 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: Optional[str]) -> bool

Parameters:
  • fileNameQString (Optional[str])

  • retError (Optional[str])

Return type:

bool

lastModified(name: str | None) QDateTime

Returns time stamp for given file name

Parameters:

name (Optional[str])

Return type:

QDateTime

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

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

Deprecated since version use: QgsRasterRenderer.createLegendNodes() instead.

Return type:

List[Tuple[str, QColor]]

opacity(self) float
Return type:

float

paletteAsPixmap(self, bandNumber: int = 1) QPixmap

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

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

Draws a preview of the rasterlayer into a QImage

Parameters:
  • size (QSize)

  • bgColor (Union[QColor)

  • format (QImage.Format = QImage.Format_ARGB32_Premultiplied)

Return type:

QImage

properties(self) Qgis.MapLayerProperties
Return type:

Qgis.MapLayerProperties

providerType(self) str

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

Return type:

str

rasterType(self) Qgis.RasterLayerType

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

Return type:

Qgis.RasterLayerType

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

Return type:

float

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

Return type:

float

readCommonStyle(self, layerElement: QDomElement, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories)

Read style data common to all layer types

readCustomProperties(self, layerNode: QDomNode, keyStartsWith: str | None = '')

Read custom properties from project file.

Parameters:
  • layerNode – note to read from

  • keyStartsWith – reads only properties starting with the specified string (or all if the string is empty)

readStyle(self, node: QDomNode, errorMessage: str | None, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool
Parameters:
Return type:

bool

readStyleManager(self, layerNode: QDomNode)

Read style manager’s configuration (if any). To be called by subclasses.

readSymbology(self, node: QDomNode, errorMessage: str | None, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool
Parameters:
Return type:

bool

readXml(self, layer_node: QDomNode, context: QgsReadWriteContext) bool
Parameters:
Return type:

bool

receivers(self, signal: PYQT_SIGNAL) int
reload(self)
renderer(self) QgsRasterRenderer | None

Returns the raster’s renderer.

See also

setRenderer()

Return type:

Optional[QgsRasterRenderer]

resampleFilter(self) QgsRasterResampleFilter | None

Returns the raster’s resample filter.

Return type:

Optional[QgsRasterResampleFilter]

resamplingStage(self) Qgis.RasterResamplingStage

Returns which stage of the pipe should apply resampling.

Added in version 3.16.

Return type:

Qgis.RasterResamplingStage

sender(self) QObject | None
senderSignalIndex(self) int
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 (QgsContrastEnhancement.ContrastEnhancementAlgorithm) – Contrast enhancement algorithm

  • limits (QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax) – 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)

Set the data provider.

Deprecated since version Use: the version with ProviderOptions instead.

setDataProvider(self, provider: Optional[str], options: QgsDataProvider.ProviderOptions, flags: Union[QgsDataProvider.ReadFlags, QgsDataProvider.ReadFlag] = QgsDataProvider.ReadFlags()) Set the data provider.

Parameters:
  • provider (Optional[str]) – provider key string, must match a valid QgsRasterDataProvider key. E.g. “gdal”, “wms”, etc.

  • options – provider options

  • flags – provider flags since QGIS 3.16

Added in version 3.2.

setDefaultContrastEnhancement(self)

Sets the default contrast enhancement

setError(self, error: QgsError)

Sets error message

setExtent(self, rect: QgsRectangle)

Sets the extent

setExtent3D(self, box: QgsBox3D)

Sets the extent

Added in version 3.36.

setLayerOrder(self, layers: Iterable[str | None])
Parameters:

layers (Iterable[Optional[str]])

setOpacity(self, opacity: float)
Parameters:

opacity (float)

setProviderType(self, providerType: str | None)

Sets the providerType (provider key)

setRenderer(self, renderer: QgsRasterRenderer | None)

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

See also

renderer()

Parameters:

renderer (Optional[QgsRasterRenderer])

setResamplingStage(self, stage: Qgis.RasterResamplingStage)

Select which stage of the pipe should apply resampling.

Added in version 3.16.

Parameters:

stage (Qgis.RasterResamplingStage)

setSubLayerVisibility(self, name: str | None, vis: bool)
Parameters:
  • name (Optional[str])

  • vis (bool)

setSubsetString(self, subset: str | None) bool

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.

setTransformContext(self, transformContext: QgsCoordinateTransformContext)

Sets the coordinate transform context to transformContext

Added in version 3.8.

Parameters:

transformContext (QgsCoordinateTransformContext)

setValid(self, valid: bool)

Sets whether layer is valid or not

showStatusMessage(self, message: str | None)
Parameters:

message (Optional[str])

subLayers(self) List[str]
Return type:

List[str]

subsetString(self) str

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

Return type:

str

Returns:

The subset string or null QString if not implemented by the provider

Added in version 3.12.

subsetStringChanged

pyqtSignal(*types, name: str = …, revision: int = …, arguments: Sequence = …) -> PYQT_SIGNAL

types is normally a sequence of individual types. Each type is either a type object or a string that is the name of a C++ type. Alternatively each type could itself be a sequence of types each describing a different overloaded signal. name is the optional C++ name of the signal. If it is not specified then the name of the class attribute that is bound to the signal is used. revision is the optional revision of the signal that is exported to QML. If it is not specified then 0 is used. arguments is the optional sequence of the names of the signal’s arguments.

Parameters:
  • name (str = ...)

  • revision (int = ...)

  • arguments (Sequence = ...)

Return type:

PYQT_SIGNAL

temporalProperties(self) QgsMapLayerTemporalProperties | None
Return type:

Optional[QgsMapLayerTemporalProperties]

timerEvent(self, a0: QTimerEvent | None)
timestamp(self) QDateTime
Return type:

QDateTime

width(self) int

Returns the width of the (unclipped) raster.

See also

height()

Return type:

int

writeCommonStyle(self, layerElement: QDomElement, document: QDomDocument, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories)

Write style data common to all layer types

writeCustomProperties(self, layerNode: QDomNode, doc: QDomDocument)

Write custom properties to project file.

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

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) – a open ended set of properties that can drive/inform the SLD encoding

Return type:

bool

Returns:

True in case of success

Added in version 3.6.

writeStyle(self, node: QDomNode, doc: QDomDocument, errorMessage: str | None, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool
Parameters:
Return type:

bool

writeStyleManager(self, layerNode: QDomNode, doc: QDomDocument)

Write style manager’s configuration (if exists). To be called by subclasses.

writeSymbology(self, a0: QDomNode, doc: QDomDocument, errorMessage: str | None, context: QgsReadWriteContext, categories: QgsMapLayer.StyleCategories | QgsMapLayer.StyleCategory = QgsMapLayer.AllStyleCategories) bool
Parameters:
Return type:

bool

writeXml(self, layer_node: QDomNode, doc: QDomDocument, context: QgsReadWriteContext) bool
Parameters:
Return type:

bool