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¶
Base classes¶
Base class for all map layer types. |
|
Interface for classes which can generate elevation profiles. |
- 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:
objectSetting options for loading raster layers.
- skipCrsValidation: bool¶
- LayerType¶
alias of
RasterLayerType
- MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 1¶
- MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 0¶
- SAMPLE_SIZE: float = 250000.0¶
- SINGLE_BAND_ENHANCEMENT_ALGORITHM: ContrastEnhancementAlgorithm = 1¶
- 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
- 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
See also
- Return type:
Optional[QgsBrightnessContrastFilter]
- canCreateRasterAttributeTable(self) bool[source]¶
Returns
Trueif the raster renderer is suitable for creation of a raster attribute table. The supported renderers areQgsPalettedRasterRendererandQgsSingleBandPseudoColorRenderer.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
Noneif the layer is invalid.- Return type:
Optional[QgsRasterDataProvider]
- virtual dataProvider(self) QgsRasterDataProvider | None[source]¶
Returns the source data provider.
This will be
Noneif 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 bothdraw()and thumbnailAsPixmap- Parameters:
theQPainter (Optional[QPainter])
myRasterViewPort (Optional[QgsRasterViewPort])
qgsMapToPixel (Optional[QgsMapToPixel] = None)
- hueSaturationFilter(self) QgsHueSaturationFilter | None[source]¶
Returns the raster’s hue/saturation filter.
See also
See also
- 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.isValidRasterFileName(fileNameQString: Optional[str]) -> bool
- Parameters:
fileNameQString (Optional[str])
retError (Optional[str])
- Return type:
bool
- labeling(self) QgsAbstractRasterLayerLabeling | None[source]¶
Access to labeling configuration. May be
Noneif labeling is not used.Note
Labels will only be rendered if
labelsEnabled()returnsTrue.See also
See also
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:
Trueif layer contains enabled labels
See also
See also
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:
- 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 theQgis.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.See also
- 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 theQgis.RasterInterfaceCapability.Size capability in order to determine whether the data provider has a native size/resolution.See also
- Return type:
float
- renderer(self) QgsRasterRenderer | None[source]¶
Returns the raster’s renderer.
See also
- Return type:
Optional[QgsRasterRenderer]
- resampleFilter(self) QgsRasterResampleFilter | None[source]¶
Returns the raster’s resample filter.
See also
See also
- Return type:
Optional[QgsRasterResampleFilter]
- resamplingStage(self) Qgis.RasterResamplingStage[source]¶
Returns which stage of the pipe should apply resampling.
See also
Added in version 3.16.
- Return type:
- 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 extentsampleSize (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.
setDataProvider(self, provider: Optional[str], options: QgsDataProvider.ProviderOptions, flags: Union[Qgis.DataProviderReadFlags, Qgis.DataProviderReadFlag] = Qgis.DataProviderReadFlags()) Set the data provider.
- Parameters:
provider (Optional[str]) – provider key string, must match a valid
QgsRasterDataProviderkey. E.g. “gdal”, “wms”, etc.options – provider options
flags – provider flags since QGIS 3.16
Added in version 3.2.
- setLabeling(self, labeling: QgsAbstractRasterLayerLabeling | None)[source]¶
Sets labeling configuration. Takes ownership of the object.
See also
Added in version 3.42.
- Parameters:
labeling (Optional[QgsAbstractRasterLayerLabeling])
- setLabelsEnabled(self, enabled: bool)[source]¶
Sets whether labels should be
enabledfor the layer.Note
Labels will only be rendered if
labelsEnabled()isTrueand a labeling object is returned bylabeling().See also
See also
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
- Parameters:
renderer (Optional[QgsRasterRenderer])
- setResamplingStage(self, stage: Qgis.RasterResamplingStage)[source]¶
Select which stage of the pipe should apply resampling.
See also
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,Falseotherwise
Added in version 3.12.
- 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]¶
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.
- 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
- Returns:
Truein case of success
Deprecated since version 3.44: Use the version with
QgsSldExportContextinstead.writeSld(self, node: QDomNode, doc: QDomDocument, context:
QgsSldExportContext) -> bool Writes the symbology of the layer into the document provided in SLD 1.1 format- Parameters:
node – the node that will have the style element added to it.
doc – the document that will have the QDomNode added.
context – export context. Errors and warnings may be retrieved from this context.
- Return type:
bool
- Returns:
Truein case of success
Added in version 3.44.