Subgroup: Map

Class: QgsMapCanvas

class qgis.gui.QgsMapCanvas

Bases: PyQt5.QtWidgets.QGraphicsView

Map canvas is a class for displaying all GIS data types on a canvas.

Methods

acceptDrops
accessibleDescription
accessibleName
actionEvent
actions
activateWindow
addAction
addActions
addScrollBarWidget
adjustSize
alignment
annotationItems Returns a list of all annotation items in the canvas.
annotationsVisible Returns true if annotations are visible within the map canvas.
antiAliasingEnabled true if antialising is enabled
autoFillBackground
backgroundBrush
backgroundRole
baseSize
blockSignals
cacheMode
canvasColor Read property of QColor bgColor.
center Get map center, in geographical coordinates
centerOn centerOn(self, QGraphicsItem)
changeEvent
childAt childAt(self, int, int) -> QWidget
childEvent
children
childrenRect
childrenRegion
clearCache Make sure to remove any rendered images from cache (does nothing if cache is not enabled)
clearExtentHistory
clearFocus
clearMask
close
closeEvent
colorCount
connectNotify
contentsMargins
contentsRect
contextMenuEvent
contextMenuPolicy
cornerWidget
create
createWindowContainer
currentLayer returns current layer (set by legend widget)
cursor
customEvent
deleteLater
depth
destroy
devType
devicePixelRatio
devicePixelRatioF
devicePixelRatioFScale
disconnect
disconnectNotify
dragEnterEvent Overridden drag enter event
dragLeaveEvent
dragMode
dragMoveEvent
drawBackground
drawForeground
drawFrame
dropEvent
dumpObjectInfo
dumpObjectTree
dynamicPropertyNames
effectiveWinId
enableAntiAliasing used to determine if anti-aliasing is enabled or not
enableMapTileRendering sets map tile rendering flag
ensurePolished
ensureVisible ensureVisible(self, QGraphicsItem, xMargin: int = 50, yMargin: int = 50)
enterEvent
event Overridden standard event to be gestures aware
eventFilter
expressionContextScope Returns a reference to the expression context scope for the map canvas.
extent Returns the current zoom extent of the map canvas
find
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]
fitInView fitInView(self, QGraphicsItem, mode: Qt.AspectRatioMode = Qt.IgnoreAspectRatio)
flashFeatureIds Causes a set of features with matching ids from a vector layer to flash within the canvas.
flashGeometries Causes a set of geometries to flash within the canvas.
focusInEvent
focusNextChild
focusNextPrevChild
focusOutEvent
focusPolicy
focusPreviousChild
focusProxy
focusWidget
font
fontInfo
fontMetrics
foregroundBrush
foregroundRole
frameGeometry
frameRect
frameShadow
frameShape
frameSize
frameStyle
frameWidth
freeze Freeze/thaw the map canvas.
fullExtent Returns the combined extent for all layers on the map canvas
geometry
getContentsMargins
getCoordinateTransform Get the current coordinate transform
grab
grabGesture
grabKeyboard
grabMouse grabMouse(self, Union[QCursor, Qt.CursorShape])
grabShortcut
graphicsEffect
graphicsProxyWidget
hasFocus
hasHeightForWidth
hasMouseTracking
hasTabletTracking
height
heightForWidth
heightMM
hide
hideEvent
horizontalScrollBar
horizontalScrollBarPolicy
inherits
initPainter
initStyleOption
inputMethodEvent
inputMethodHints
inputMethodQuery
insertAction
insertActions
installEventFilter
invalidateScene
isActiveWindow
isAncestorOf
isCachingEnabled Check whether images of rendered layers are curerently being cached
isDrawing Find out whether rendering is in progress
isEnabled
isEnabledTo
isFrozen Returns true if canvas is frozen.
isFullScreen
isHidden
isInteractive
isLeftToRight
isMaximized
isMinimized
isModal
isParallelRenderingEnabled Check whether the layers are rendered in parallel or sequentially
isRightToLeft
isSignalConnected
isTransformed
isVisible
isVisibleTo
isWidgetType
isWindow
isWindowModified
isWindowType
itemAt itemAt(self, int, int) -> QGraphicsItem
items items(self, QPoint) -> List[QGraphicsItem]
keyPressEvent Overridden key press event
keyReleaseEvent Overridden key release event
keyboardGrabber
killTimer
labelingEngineSettings Returns global labeling engine settings from the internal map settings
labelingResults Get access to the labeling results (may be null)
layer return the map layer at position index in the layer stack
layerCount return number of layers on the map
layerStateChange This slot is connected to the visibility change of one or more layers
layerStyleOverrides Returns the stored overrides of styles for layers.
layers Return the list of layers shown within the map canvas.
layout
layoutDirection
leaveEvent
lineWidth
locale
logicalDpiX
logicalDpiY
lower
magnificationFactor Returns the magnification factor
mapFrom
mapFromGlobal
mapFromParent
mapFromScene mapFromScene(self, QRectF) -> QPolygon
mapSettings Get access to properties used for map rendering
mapTo
mapToGlobal
mapToParent
mapToScene mapToScene(self, QRect) -> QPolygonF
mapTool Returns the currently active tool
mapUnits Convience function for returning the current canvas map units.
mapUnitsPerPixel Returns the mapUnitsPerPixel (map units per pixel) for the canvas
mapUpdateInterval Find out how often map preview should be updated while it is being rendered (in milliseconds)
mask
maximumHeight
maximumSize
maximumViewportSize
maximumWidth
metaObject
metric
midLineWidth
minimumHeight
minimumSize
minimumSizeHint
minimumWidth
mouseDoubleClickEvent Overridden mouse double-click event
mouseGrabber
mouseLastXY returns last position of mouse cursor
mouseMoveEvent Overridden mouse move event
mousePressEvent Overridden mouse press event
mouseReleaseEvent Overridden mouse release event
move move(self, int, int)
moveCanvasContents called when panning is in action, reset indicates end of panning
moveEvent
moveToThread
nativeEvent
nativeParentWidget
nextInFocusChain
normalGeometry
objectName
optimizationFlags
overrideWindowFlags
overrideWindowState
paintEngine
paintEvent Overridden paint event
paintingActive
palette
panAction Called when mouse is moving and pan is activated
panActionEnd Ends pan action and redraws the canvas.
panToFeatureIds Centers canvas extent to feature ids
panToSelected Pan to the selected features of current (vector) layer keeping same extent.
parent
parentWidget
physicalDpiX
physicalDpiY
pos
previewJobsEnabled Returns true if canvas map preview jobs (low priority render jobs which render portions of the view just outside of the canvas extent, to allow preview of these out-of-canvas areas when panning or zooming out the map) are enabled for the canvas.
previewMode Returns the current preview mode for the map canvas.
previewModeEnabled Returns whether a preview mode is enabled for the map canvas
previousInFocusChain
property
pyqtConfigure Each keyword argument is either the name of a Qt property or a Qt signal.
raise_
readProject called to read map canvas settings from project
receivers
rect
refresh Repaints the canvas map
refreshAllLayers Reload all layers, clear the cache and refresh the canvas
releaseKeyboard
releaseMouse
releaseShortcut
removeAction
removeEventFilter
render
renderFlag Returns true if canvas render is disabled as a result of user disabling renders via the GUI.
renderHints
repaint repaint(self, int, int, int, int)
resetCachedContent
resetTransform
resize resize(self, int, int)
resizeAnchor
resizeEvent Overridden resize event
restoreGeometry
rotate
rotation Get the current map canvas rotation in clockwise degrees
rubberBandRect
rubberBandSelectionMode
saveAsImage Save the convtents of the map canvas to disk as an image
saveGeometry
scale Returns the last reported scale of the canvas.
scaleLocked Returns whether the scale is locked, so zooming can be performed using magnication.
scene
sceneRect
scroll scroll(self, int, int, QRect)
scrollBarWidgets
scrollContentsBy
selectionChangedSlot Receives signal about selection change, and pass it on with layer info
selectionColor Returns color for selected features
sender
senderSignalIndex
setAcceptDrops
setAccessibleDescription
setAccessibleName
setAlignment
setAnnotationsVisible Sets whether annotations are visible in the canvas.
setAttribute
setAutoFillBackground
setBackgroundBrush
setBackgroundRole
setBaseSize setBaseSize(self, QSize)
setCacheMode
setCachingEnabled Set whether to cache images of rendered layers
setCanvasColor Write property of QColor bgColor.
setCenter Set the center of the map canvas, in geographical coordinates
setContentsMargins setContentsMargins(self, QMargins)
setContextMenuPolicy
setCornerWidget
setCurrentLayer
setCursor
setDestinationCrs sets destination coordinate reference system
setDisabled
setDragMode
setEnabled
setExpressionContextScope Sets an expression context scope for the map canvas.
setExtent Set the extent of the map canvas
setFixedHeight
setFixedSize setFixedSize(self, int, int)
setFixedWidth
setFocus setFocus(self, Qt.FocusReason)
setFocusPolicy
setFocusProxy
setFont
setForegroundBrush
setForegroundRole
setFrameRect
setFrameShadow
setFrameShape
setFrameStyle
setGeometry setGeometry(self, int, int, int, int)
setGraphicsEffect
setHidden
setHorizontalScrollBar
setHorizontalScrollBarPolicy
setInputMethodHints
setInteractive
setLabelingEngineSettings Sets global labeling engine settings in the internal map settings
setLayerStyleOverrides Sets the stored overrides of styles for rendering layers.
setLayers Sets the list of layers that should be shown in the canvas.
setLayout
setLayoutDirection
setLineWidth
setLocale
setMagnificationFactor Sets the factor of magnification to apply to the map canvas.
setMapSettingsFlags Resets the flags for the canvas’ map settings.
setMapTool Sets the map tool currently being used on the canvas
setMapUpdateInterval Set how often map preview should be updated while it is being rendered (in milliseconds)
setMask setMask(self, QRegion)
setMaximumHeight
setMaximumSize setMaximumSize(self, QSize)
setMaximumWidth
setMidLineWidth
setMinimumHeight
setMinimumSize setMinimumSize(self, QSize)
setMinimumWidth
setMouseTracking
setObjectName
setOptimizationFlag
setOptimizationFlags
setPalette
setParallelRenderingEnabled Set whether the layers are rendered in parallel or sequentially
setParent setParent(self, QWidget, Union[Qt.WindowFlags, Qt.WindowType])
setPreviewJobsEnabled Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just outside of the canvas extent, to allow preview of these out-of-canvas areas when panning or zooming out the map) are enabled for the canvas.
setPreviewMode Sets a preview mode for the map canvas.
setPreviewModeEnabled Enables a preview mode for the map canvas
setProperty
setRenderFlag Sets whether a user has disabled canvas renders via the GUI.
setRenderHint
setRenderHints
setResizeAnchor
setRotation Set the rotation of the map canvas in clockwise degrees
setRubberBandSelectionMode
setScaleLocked Lock the scale, so zooming can be performed using magnication
setScene
setSceneRect setSceneRect(self, float, float, float, float)
setSegmentationTolerance Sets the segmentation tolerance applied when rendering curved geometries
setSegmentationToleranceType Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation)
setSelectionColor Set color of selected vector features
setShortcutAutoRepeat
setShortcutEnabled
setSizeAdjustPolicy
setSizeIncrement setSizeIncrement(self, QSize)
setSizePolicy setSizePolicy(self, QSizePolicy.Policy, QSizePolicy.Policy)
setSnappingUtils Assign an instance of snapping utils to the map canvas.
setStatusTip
setStyle
setStyleSheet
setTabOrder
setTabletTracking
setTheme Sets a map theme to show in the canvas.
setToolTip
setToolTipDuration
setTransform
setTransformationAnchor
setUpdatesEnabled
setVerticalScrollBar
setVerticalScrollBarPolicy
setViewport
setViewportMargins
setViewportUpdateMode
setVisible
setWhatsThis
setWheelFactor set wheel zoom factor (should be greater than 1)
setWindowFilePath
setWindowFlag
setWindowFlags
setWindowIcon
setWindowIconText
setWindowModality
setWindowModified
setWindowOpacity
setWindowRole
setWindowState
setWindowTitle
setupViewport
sharedPainter
shear
show
showEvent
showFullScreen
showMaximized
showMinimized
showNormal
signalsBlocked
size
sizeAdjustPolicy
sizeHint
sizeIncrement
sizePolicy
snappingUtils Return snapping utility class that is associated with map canvas.
stackUnder
startTimer
statusTip
stopRendering stop rendering (if there is any right now)
style
styleSheet
tabletEvent
testAttribute
theme Returns the map’s theme shown in the canvas, if set.
thread
timerEvent
toolTip
toolTipDuration
tr
transform
transformationAnchor
translate
underMouse
ungrabGesture
unsetCursor
unsetLayoutDirection
unsetLocale
unsetMapTool Unset the current map tool or last non zoom tool
update update(self, QRect)
updateCanvasItemPositions called on resize or changed extent to notify canvas items to change their rectangle
updateGeometry
updateMicroFocus
updateScale Emits signal scaleChanged to update scale in main window
updateScene
updateSceneRect
updatesEnabled
verticalScrollBar
verticalScrollBarPolicy
viewport
viewportEvent
viewportMargins
viewportSizeHint
viewportTransform
viewportUpdateMode
visibleRegion
waitWhileRendering Blocks until the rendering job has finished.
whatsThis
wheelEvent Overridden mouse wheel event
width
widthMM
winId
window
windowFilePath
windowFlags
windowHandle
windowIcon
windowIconText
windowModality
windowOpacity
windowRole
windowState
windowTitle
windowType
writeProject called to write map canvas settings to project
x
y
zoomByFactor Zoom with the factor supplied.
zoomIn Zoom in with fixed factor
zoomOut Zoom out with fixed factor
zoomScale Zooms the canvas to a specific scale.
zoomToFeatureExtent Zooms to feature extent.
zoomToFeatureIds Set canvas extent to the bounding box of a set of features
zoomToFullExtent Zoom to the full extent of all layers
zoomToNextExtent Zoom to the next extent (view)
zoomToPreviousExtent Zoom to the previous extent (view)
zoomToSelected Zoom to the extent of the selected features of current (vector) layer.
zoomWithCenter Zooms in/out with a given center

Attributes

AdjustIgnored
AdjustToContents
AdjustToContentsOnFirstShow
AnchorUnderMouse
AnchorViewCenter
BoundingRectViewportUpdate
Box
CacheBackground
CacheNone
DontAdjustForAntialiasing
DontClipPainter
DontSavePainterState
DrawChildren
DrawWindowBackground
FullViewportUpdate
HLine
IgnoreMask
MinimalViewportUpdate
NoAnchor
NoDrag
NoFrame
NoViewportUpdate
Panel
PdmDepth
PdmDevicePixelRatio
PdmDevicePixelRatioScaled
PdmDpiX
PdmDpiY
PdmHeight
PdmHeightMM
PdmNumColors
PdmPhysicalDpiX
PdmPhysicalDpiY
PdmWidth
PdmWidthMM
Plain
Raised
RubberBandDrag
ScrollHandDrag
Shadow_Mask
Shape_Mask
SmartViewportUpdate
StyledPanel
Sunken
VLine
WinPanel
canvasColorChanged Emitted when canvas background color changes
currentLayerChanged Emitted when the current layer is changed
customContextMenuRequested customContextMenuRequested(self, QPoint) [signal]
destinationCrsChanged Emitted when map CRS has changed
destroyed destroyed(self, QObject = None) [signal]
extentsChanged Emitted when the extents of the map change [signal]
keyPressed Emit key press event [signal]
keyReleased Emit key release event [signal]
layerStyleOverridesChanged Emitted when the configuration of overridden layer styles changes
layersChanged Emitted when a new set of layers has been received [signal]
magnificationChanged Emitted when the scale of the map changes
mapCanvasRefreshed Emitted when canvas finished a refresh request.
mapToolSet Emit map tool changed with the old tool
messageEmitted emit a message (usually to be displayed in a message bar) [signal]
objectNameChanged objectNameChanged(self, str) [signal]
renderComplete TODO: deprecate when decorations are reimplemented as map canvas items
renderStarting Emitted when the canvas is about to be rendered.
rotationChanged Emitted when the rotation of the map changes
rubberBandChanged rubberBandChanged(self, QRect, Union[QPointF, QPoint], Union[QPointF, QPoint]) [signal]
scaleChanged Emitted when the scale of the map changes [signal]
selectionChanged Emitted when selection in any layer gets changed [signal]
staticMetaObject
themeChanged Emitted when the canvas has been assigned a different map theme.
transformContextChanged Emitted when the canvas transform context is changed.
windowIconChanged windowIconChanged(self, QIcon) [signal]
windowIconTextChanged windowIconTextChanged(self, str) [signal]
windowTitleChanged windowTitleChanged(self, str) [signal]
xyCoordinates Emits current mouse position
zoomLastStatusChanged Emitted when zoom last status changed [signal]
zoomNextStatusChanged Emitted when zoom next status changed [signal]
actionEvent()
annotationItems(self) → object

Returns a list of all annotation items in the canvas.

New in version 3.0.

annotationsVisible(self) → bool

Returns true if annotations are visible within the map canvas.

New in version 3.0.

antiAliasingEnabled(self) → bool

true if antialising is enabled

canvasColor(self) → QColor

Read property of QColor bgColor.

canvasColorChanged

Emitted when canvas background color changes

New in version 3.0: [signal]

center(self) → QgsPointXY

Get map center, in geographical coordinates

New in version 2.8.

changeEvent()
childEvent()
clearCache(self)

Make sure to remove any rendered images from cache (does nothing if cache is not enabled)

New in version 2.4.

clearExtentHistory(self)
closeEvent()
connectNotify()
contextMenuEvent()
create()
currentLayer(self) → QgsMapLayer

returns current layer (set by legend widget)

currentLayerChanged

Emitted when the current layer is changed

New in version 2.8: [signal]

customEvent()
destinationCrsChanged

Emitted when map CRS has changed

New in version 2.4: [signal]

destroy()
disconnectNotify()
dragEnterEvent(self, e: QDragEnterEvent)

Overridden drag enter event

dragLeaveEvent()
dragMoveEvent()
drawBackground()
drawForeground()
drawFrame()
dropEvent()
enableAntiAliasing(self, flag: bool)

used to determine if anti-aliasing is enabled or not

enableMapTileRendering(self, flag: bool)

sets map tile rendering flag

enterEvent()
event(self, e: QEvent) → bool

Overridden standard event to be gestures aware

eventFilter()
expressionContextScope(self) → QgsExpressionContextScope

Returns a reference to the expression context scope for the map canvas. This scope is injected into the expression context used for rendering the map, and can be used to apply specific variable overrides for expression evaluation for the map canvas render.

New in version 2.12.

extent(self) → QgsRectangle

Returns the current zoom extent of the map canvas

extentsChanged

Emitted when the extents of the map change [signal]

flashFeatureIds(self, layer: QgsVectorLayer, ids: object, startColor: Union[QColor, Qt.GlobalColor, QGradient] = QColor(255, 0, 0, 255), endColor: Union[QColor, Qt.GlobalColor, QGradient] = QColor(255, 0, 0, 0), flashes: int = 3, duration: int = 500)

Causes a set of features with matching ids from a vector layer to flash within the canvas.

The startColor and endColor can be specified, along with the number of flashes and duration of each flash (in milliseconds).

Note

If the features or geometries are already available, flashGeometries() is much more efficient.

New in version 3.0.

flashGeometries(self, geometries: object, crs: QgsCoordinateReferenceSystem = QgsCoordinateReferenceSystem(), startColor: Union[QColor, Qt.GlobalColor, QGradient] = QColor(255, 0, 0, 255), endColor: Union[QColor, Qt.GlobalColor, QGradient] = QColor(255, 0, 0, 0), flashes: int = 3, duration: int = 500)

Causes a set of geometries to flash within the canvas.

If crs is a valid coordinate reference system, the geometries will be automatically transformed from this CRS to the canvas CRS.

The startColor and endColor can be specified, along with the number of flashes and duration of each flash (in milliseconds).

New in version 3.0.

focusInEvent()
focusNextChild()
focusNextPrevChild()
focusOutEvent()
focusPreviousChild()
freeze(self, frozen: bool = True)

Freeze/thaw the map canvas. This is used to prevent the canvas from responding to events while layers are being added/removed etc.

Parameters:frozen – Boolean specifying if the canvas should be frozen (true) or

thawed (false). Default is true.

See also

isFrozen()

See also

setRenderFlag()

while setRenderFlag() should only be used when users disable rendering via GUI.

fullExtent(self) → QgsRectangle

Returns the combined extent for all layers on the map canvas

getCoordinateTransform(self) → QgsMapToPixel

Get the current coordinate transform

hideEvent()
initPainter()
initStyleOption()
inputMethodEvent()
isCachingEnabled(self) → bool

Check whether images of rendered layers are curerently being cached

New in version 2.4.

isDrawing(self) → bool

Find out whether rendering is in progress

isFrozen(self) → bool

Returns true if canvas is frozen.

See also

renderFlag()

have been halted programmatically, while renderFlag() should be used to determine whether a user has disabled rendering via GUI.

See also

freeze()

isParallelRenderingEnabled(self) → bool

Check whether the layers are rendered in parallel or sequentially

New in version 2.4.

isSignalConnected()
keyPressEvent(self, e: QKeyEvent)

Overridden key press event

keyPressed

Emit key press event [signal]

keyReleaseEvent(self, e: QKeyEvent)

Overridden key release event

keyReleased

Emit key release event [signal]

labelingEngineSettings(self) → QgsLabelingEngineSettings

Returns global labeling engine settings from the internal map settings

New in version 3.0.

labelingResults(self) → QgsLabelingResults

Get access to the labeling results (may be null)

New in version 2.4.

layer(self, index: int) → QgsMapLayer

return the map layer at position index in the layer stack

layerCount(self) → int

return number of layers on the map

layerStateChange(self)

This slot is connected to the visibility change of one or more layers

layerStyleOverrides(self) → Dict[str, str]

Returns the stored overrides of styles for layers.

New in version 2.12.

layerStyleOverridesChanged

Emitted when the configuration of overridden layer styles changes

New in version 2.12: [signal]

layers(self) → List[QgsMapLayer]

Return the list of layers shown within the map canvas.

See also

setLayers()

layersChanged

Emitted when a new set of layers has been received [signal]

leaveEvent()
magnificationChanged

Emitted when the scale of the map changes

New in version 2.16: [signal]

magnificationFactor(self) → float

Returns the magnification factor

New in version 2.16.

mapCanvasRefreshed

Emitted when canvas finished a refresh request. [signal]

mapSettings(self) → QgsMapSettings

Get access to properties used for map rendering

New in version 2.4.

mapTool(self) → QgsMapTool

Returns the currently active tool

mapToolSet

Emit map tool changed with the old tool

New in version 2.3: [signal]

mapUnits(self) → QgsUnitTypes.DistanceUnit

Convience function for returning the current canvas map units. The map units are dictated by the canvas’ destinationCrs() map units.

mapUnitsPerPixel(self) → float

Returns the mapUnitsPerPixel (map units per pixel) for the canvas

mapUpdateInterval(self) → int

Find out how often map preview should be updated while it is being rendered (in milliseconds)

New in version 2.4.

messageEmitted

emit a message (usually to be displayed in a message bar) [signal]

metric()
mouseDoubleClickEvent(self, e: QMouseEvent)

Overridden mouse double-click event

mouseLastXY(self) → QPoint

returns last position of mouse cursor

mouseMoveEvent(self, e: QMouseEvent)

Overridden mouse move event

mousePressEvent(self, e: QMouseEvent)

Overridden mouse press event

mouseReleaseEvent(self, e: QMouseEvent)

Overridden mouse release event

moveCanvasContents(self, reset: bool = False)

called when panning is in action, reset indicates end of panning

moveEvent()
nativeEvent()
paintEvent(self, e: QPaintEvent)

Overridden paint event

panAction(self, event: QMouseEvent)

Called when mouse is moving and pan is activated

panActionEnd(self, releasePoint: QPoint)

Ends pan action and redraws the canvas.

panToFeatureIds(self, layer: QgsVectorLayer, ids: object)

Centers canvas extent to feature ids

Parameters:
  • layer – the vector layer
  • ids – the feature ids*
panToSelected(self, layer: QgsVectorLayer = None)

Pan to the selected features of current (vector) layer keeping same extent.

previewJobsEnabled(self) → bool

Returns true if canvas map preview jobs (low priority render jobs which render portions of the view just outside of the canvas extent, to allow preview of these out-of-canvas areas when panning or zooming out the map) are enabled for the canvas.

New in version 3.0.

previewMode(self) → QgsPreviewEffect.PreviewMode

Returns the current preview mode for the map canvas. This setting only has an effect if previewModeEnabled is true.

Returns:preview mode for map canvas

See also

setPreviewMode()

New in version 2.3.

previewModeEnabled(self) → bool

Returns whether a preview mode is enabled for the map canvas

Returns:true if a preview mode is currently enabled

See also

previewMode()

New in version 2.3.

readProject(self, QDomDocument)

called to read map canvas settings from project

receivers()
refresh(self)

Repaints the canvas map

refreshAllLayers(self)

Reload all layers, clear the cache and refresh the canvas

New in version 2.9.

renderComplete

TODO: deprecate when decorations are reimplemented as map canvas items - anything related to rendering progress is not visible outside of map canvas - additional drawing shall be done directly within the renderer job or independently as a map canvas item [signal]

renderFlag(self) → bool

Returns true if canvas render is disabled as a result of user disabling renders via the GUI.

See also

setRenderFlag()

See also

isFrozen()

have been halted programmatically, while renderFlag() should be used to determine whether a user has disabled rendering via GUI.

renderStarting

Emitted when the canvas is about to be rendered. [signal]

resizeEvent(self, e: QResizeEvent)

Overridden resize event

rotation(self) → float

Get the current map canvas rotation in clockwise degrees

New in version 2.8.

rotationChanged

Emitted when the rotation of the map changes

New in version 2.8: [signal]

saveAsImage(self, fileName: str, QPixmap: QPixmap = None, a2: str = '')

Save the convtents of the map canvas to disk as an image

scale(self) → float

Returns the last reported scale of the canvas. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.

scaleChanged

Emitted when the scale of the map changes [signal]

scaleLocked(self) → bool

Returns whether the scale is locked, so zooming can be performed using magnication.

New in version 2.16.

See also

setScaleLocked()

scrollContentsBy()
selectionChanged

Emitted when selection in any layer gets changed [signal]

selectionChangedSlot(self)

Receives signal about selection change, and pass it on with layer info

selectionColor(self) → QColor

Returns color for selected features

New in version 3.0.

sender()
senderSignalIndex()
setAnnotationsVisible(self, visible: bool)

Sets whether annotations are visible in the canvas.

New in version 3.0.

setCachingEnabled(self, enabled: bool)

Set whether to cache images of rendered layers

New in version 2.4.

setCanvasColor(self, _newVal: Union[QColor, Qt.GlobalColor, QGradient])

Write property of QColor bgColor.

setCenter(self, center: QgsPointXY)

Set the center of the map canvas, in geographical coordinates

New in version 2.8.

setCurrentLayer(self, layer: QgsMapLayer)
setDestinationCrs(self, crs: QgsCoordinateReferenceSystem)

sets destination coordinate reference system

New in version 2.4.

setExpressionContextScope(self, scope: QgsExpressionContextScope)

Sets an expression context scope for the map canvas. This scope is injected into the expression context used for rendering the map, and can be used to apply specific variable overrides for expression evaluation for the map canvas render. This method will overwrite the existing expression context scope for the canvas.

Parameters:scope – new expression context scope

New in version 2.12.

setExtent(self, r: QgsRectangle, magnified: bool = False)

Set the extent of the map canvas

setLabelingEngineSettings(self, settings: QgsLabelingEngineSettings)

Sets global labeling engine settings in the internal map settings

New in version 3.0.

setLayerStyleOverrides(self, overrides: Dict[str, str])

Sets the stored overrides of styles for rendering layers.

If the map canvas has been associated with a map theme via a call to setTheme(), then any calls to setLayerStyleOverrides() are ignored. It is necessary to first clear the theme association by calling setTheme() with an empty string before setLayerStyleOverrides() calls can be made.

New in version 2.12.

setLayers(self, layers: Iterable[QgsMapLayer])

Sets the list of layers that should be shown in the canvas.

If the map canvas has been associated with a map theme via a call to setTheme(), then any calls to setLayers() are ignored. It is necessary to first clear the theme association by calling setTheme() with an empty string before setLayers() calls can be made.

New in version 3.0.

See also

layers()

setMagnificationFactor(self, factor: float)

Sets the factor of magnification to apply to the map canvas. Indeed, we increase/decrease the DPI of the map settings according to this factor in order to render marker point, labels, … bigger.

New in version 2.16.

setMapSettingsFlags(self, flags: Union[QgsMapSettings.Flags, QgsMapSettings.Flag])

Resets the flags for the canvas’ map settings.

New in version 3.0.

setMapTool(self, mapTool: QgsMapTool, clean: bool = False)

Sets the map tool currently being used on the canvas

setMapUpdateInterval(self, timeMilliseconds: int)

Set how often map preview should be updated while it is being rendered (in milliseconds)

New in version 2.4.

setParallelRenderingEnabled(self, enabled: bool)

Set whether the layers are rendered in parallel or sequentially

New in version 2.4.

setPreviewJobsEnabled(self, enabled: bool)

Sets whether canvas map preview jobs (low priority render jobs which render portions of the view just outside of the canvas extent, to allow preview of these out-of-canvas areas when panning or zooming out the map) are enabled for the canvas.

New in version 3.0.

setPreviewMode(self, mode: QgsPreviewEffect.PreviewMode)

Sets a preview mode for the map canvas. This setting only has an effect if previewModeEnabled is true.

Parameters:mode – preview mode for the canvas

See also

previewMode()

New in version 2.3.

setPreviewModeEnabled(self, previewEnabled: bool)

Enables a preview mode for the map canvas

Parameters:previewEnabled – set to true to enable a preview mode

See also

setPreviewMode()

New in version 2.3.

setRenderFlag(self, flag: bool)

Sets whether a user has disabled canvas renders via the GUI.

Parameters:flag – set to false to indicate that user has disabled renders

See also

renderFlag()

See also

freeze()

while setRenderFlag() should only be used when users disable rendering via GUI.

setRotation(self, degrees: float)

Set the rotation of the map canvas in clockwise degrees

New in version 2.8.

setScaleLocked(self, isLocked: bool)

Lock the scale, so zooming can be performed using magnication

New in version 2.16.

See also

scaleLocked()

setSegmentationTolerance(self, tolerance: float)

Sets the segmentation tolerance applied when rendering curved geometries

Parameters:tolerance – the segmentation tolerance*
setSegmentationToleranceType(self, type: QgsAbstractGeometry.SegmentationToleranceType)

Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation)

Parameters:type – the segmentation tolerance typename*
setSelectionColor(self, color: Union[QColor, Qt.GlobalColor, QGradient])

Set color of selected vector features

New in version 2.4.

setSnappingUtils(self, utils: QgsSnappingUtils)

Assign an instance of snapping utils to the map canvas. The instance is not owned by the canvas, so it is possible to use one instance in multiple canvases.

For main canvas in QGIS, do not associate a different instance from the existing one (it is updated from the project’s snapping configuration).

New in version 2.8.

setTheme(self, theme: str)

Sets a map theme to show in the canvas. The theme name must match a theme present in the associated project’s QgsMapThemeCollection.

When the canvas is associated to a map theme, it will automatically follow the layer selection and layer styles from that theme. Calls to setLayers() or setLayerStyleOverrides() will have no effect, and canvases associated with a QgsLayerTreeMapCanvasBridge will no longer synchronize their state with the layer tree. In these cases it is necessary to call setTheme() with an empty string to clear the theme association and allow map updates with setLayers(), setLayerStyleOverrides(), or via QgsLayerTreeMapCanvasBridge.

If an empty string is passed then the current theme association will be cleared.

New in version 3.0.

See also

theme()

setViewportMargins()
setWheelFactor(self, factor: float)

set wheel zoom factor (should be greater than 1)

setupViewport()
sharedPainter()
showEvent()
snappingUtils(self) → QgsSnappingUtils

Return snapping utility class that is associated with map canvas. If no snapping utils instance has been associated previously, an internal will be created for convenience (so map tools do not need to test for existence of the instance).

Main canvas in QGIS returns an instance which is always up-to-date with the project’s snapping configuration.

New in version 2.8.

stopRendering(self)

stop rendering (if there is any right now)

New in version 2.4.

tabletEvent()
theme(self) → str

Returns the map’s theme shown in the canvas, if set.

New in version 3.0.

See also

setTheme()

themeChanged

Emitted when the canvas has been assigned a different map theme.

See also

setTheme()

New in version 3.0: [signal]

timerEvent()
transformContextChanged

Emitted when the canvas transform context is changed.

New in version 3.0: [signal]

unsetMapTool(self, mapTool: QgsMapTool)

Unset the current map tool or last non zoom tool

This is called from destructor of map tools to make sure that this map tool won’t be used any more. You don’t have to call it manually, QgsMapTool takes care of it.

updateCanvasItemPositions(self)

called on resize or changed extent to notify canvas items to change their rectangle

updateMicroFocus()
updateScale(self)

Emits signal scaleChanged to update scale in main window

viewportEvent()
viewportMargins()
viewportSizeHint()
waitWhileRendering(self)

Blocks until the rendering job has finished.

In almost all cases you do NOT want to call this, as it will hang the UI until the rendering job is complete. It’s included in API solely for unit testing and standalone Python scripts.

New in version 3.0.

wheelEvent(self, e: QWheelEvent)

Overridden mouse wheel event

writeProject(self, QDomDocument)

called to write map canvas settings to project

xyCoordinates

Emits current mouse position

Note

changed in 1.3 * [signal]

zoomByFactor(self, scaleFactor: float, center: QgsPointXY = None)

Zoom with the factor supplied. Factor > 1 zooms out, interval (0,1) zooms in If point is given, re-center on it

zoomIn(self)

Zoom in with fixed factor

zoomLastStatusChanged

Emitted when zoom last status changed [signal]

zoomNextStatusChanged

Emitted when zoom next status changed [signal]

zoomOut(self)

Zoom out with fixed factor

zoomScale(self, scale: float)

Zooms the canvas to a specific scale. The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.

zoomToFeatureExtent(self, rect: QgsRectangle)

Zooms to feature extent. Adds a small margin around the extent and does a pan if rect is empty (point extent)

zoomToFeatureIds(self, layer: QgsVectorLayer, ids: object)

Set canvas extent to the bounding box of a set of features

Parameters:
  • layer – the vector layer
  • ids – the feature ids*
zoomToFullExtent(self)

Zoom to the full extent of all layers

zoomToNextExtent(self)

Zoom to the next extent (view)

zoomToPreviousExtent(self)

Zoom to the previous extent (view)

zoomToSelected(self, layer: QgsVectorLayer = None)

Zoom to the extent of the selected features of current (vector) layer.

Parameters:layer – optionally specify different than current layer
zoomWithCenter(self, x: int, y: int, zoomIn: bool)

Zooms in/out with a given center