PySide6.QtWidgets.QGraphicsView¶
- class QGraphicsView¶
The
QGraphicsViewclass provides a widget for displaying the contents of aQGraphicsScene. More…Synopsis¶
Properties¶
alignmentᅟ- The alignment of the scene in the view when the whole scene is visiblebackgroundBrushᅟ- The background brush of the scenecacheModeᅟ- Which parts of the view are cacheddragModeᅟ- The behavior for dragging the mouse over the scene while the left mouse button is pressedforegroundBrushᅟ- The foreground brush of the sceneinteractiveᅟ- Whether the view allows scene interactionoptimizationFlagsᅟ- Flags that can be used to tune QGraphicsView’s performancerenderHintsᅟ- The default render hints for the viewresizeAnchorᅟ- How the view should position the scene when the view is resizedrubberBandSelectionModeᅟ- The behavior for selecting items with a rubber band selection rectanglesceneRectᅟ- The area of the scene visualized by this viewtransformationAnchorᅟ- How the view should position the scene during transformationsviewportUpdateModeᅟ- How the viewport should update its contents
Methods¶
def
__init__()def
alignment()def
cacheMode()def
centerOn()def
dragMode()def
ensureVisible()def
fitInView()def
isInteractive()def
isTransformed()def
itemAt()def
items()def
mapFromScene()def
mapToScene()def
render()def
renderHints()def
resetTransform()def
resizeAnchor()def
rotate()def
rubberBandRect()def
scale()def
scene()def
sceneRect()def
setAlignment()def
setCacheMode()def
setDragMode()def
setInteractive()def
setRenderHint()def
setRenderHints()def
setScene()def
setSceneRect()def
setTransform()def
shear()def
transform()def
translate()
Virtual methods¶
def
drawBackground()def
drawForeground()def
drawItems()
Slots¶
def
updateScene()
Signals¶
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QGraphicsViewvisualizes the contents of aQGraphicsScenein a scrollable viewport. To create a scene with geometrical items, seeQGraphicsScene‘s documentation.QGraphicsViewis part of the Graphics View Framework .To visualize a scene, you start by constructing a
QGraphicsViewobject, passing the address of the scene you want to visualize toQGraphicsView‘s constructor. Alternatively, you can callsetScene()to set the scene at a later point. After you callshow(), the view will by default scroll to the center of the scene and display any items that are visible at this point. For example:scene = QGraphicsScene() scene.addText("Hello, world!") view = QGraphicsView(scene) view.show()
You can explicitly scroll to any position on the scene by using the scroll bars, or by calling
centerOn(). By passing a point tocenterOn(),QGraphicsViewwill scroll its viewport to ensure that the point is centered in the view. An overload is provided for scrolling to aQGraphicsItem, in which caseQGraphicsViewwill see to that the center of the item is centered in the view. If all you want is to ensure that a certain area is visible, (but not necessarily centered,) you can callensureVisible()instead.QGraphicsViewcan be used to visualize a whole scene, or only parts of it. The visualized area is by default detected automatically when the view is displayed for the first time (by callingitemsBoundingRect()). To set the visualized area rectangle yourself, you can callsetSceneRect(). This will adjust the scroll bars’ ranges appropriately. Note that although the scene supports a virtually unlimited size, the range of the scroll bars will never exceed the range of an integer (INT_MIN, INT_MAX).QGraphicsViewvisualizes the scene by callingrender(). By default, the items are drawn onto the viewport by using a regular QPainter, and using default render hints. To change the default render hints thatQGraphicsViewpasses to QPainter when painting items, you can callsetRenderHints().By default,
QGraphicsViewprovides a regularQWidgetfor the viewport widget. You can access this widget by callingviewport(), or you can replace it by callingsetViewport(). To render using OpenGL, simply call setViewport(new QOpenGLWidget).QGraphicsViewtakes ownership of the viewport widget.QGraphicsViewsupports affine transformations, using QTransform. You can either pass a matrix tosetTransform(), or you can call one of the convenience functionsrotate(),scale(),translate()orshear(). The most two common transformations are scaling, which is used to implement zooming, and rotation.QGraphicsViewkeeps the center of the view fixed during a transformation. Because of the scene alignment (setAlignment()), translating the view will have no visual impact.You can interact with the items on the scene by using the mouse and keyboard.
QGraphicsViewtranslates the mouse and key events into scene events, (events that inheritQGraphicsSceneEvent,), and forward them to the visualized scene. In the end, it’s the individual item that handles the events and reacts to them. For example, if you click on a selectable item, the item will typically let the scene know that it has been selected, and it will also redraw itself to display a selection rectangle. Similarly, if you click and drag the mouse to move a movable item, it’s the item that handles the mouse moves and moves itself. Item interaction is enabled by default, and you can toggle it by callingsetInteractive().You can also provide your own custom scene interaction, by creating a subclass of
QGraphicsView, and reimplementing the mouse and key event handlers. To simplify how you programmatically interact with items in the view,QGraphicsViewprovides the mapping functionsmapToScene()andmapFromScene(), and the item accessorsitems()anditemAt(). These functions allow you to map points, rectangles, polygons and paths between view coordinates and scene coordinates, and to find items on the scene using view coordinates.When using a QOpenGLWidget as a viewport, stereoscopic rendering is supported. This is done using the same pattern as QOpenGLWidget::paintGL. To enable it, enable the QSurfaceFormat::StereoBuffers flag. Because of how the flag is handled internally, set QSurfaceFormat::StereoBuffers flag globally before the window is created using QSurfaceFormat::setDefaultFormat(). If the flag is enabled and there is hardware support for stereoscopic rendering, then
drawBackground()anddrawForeground()will be triggered twice each frame. Call QOpenGLWidget::currentTargetBuffer() to query which buffer is currently being drawn to.
Note
Using an OpenGL viewport limits the ability to use
QGraphicsProxyWidget. Not all combinations of widgets and styles can be supported with such a setup. You should carefully test your UI and make the necessary adjustments.- class ViewportAnchor¶
This enums describe the possible anchors that
QGraphicsViewcan use when the user resizes the view or when the view is transformed.Constant
Description
QGraphicsView.ViewportAnchor.NoAnchor
No anchor, i.e. the view leaves the scene’s position unchanged.
QGraphicsView.ViewportAnchor.AnchorViewCenter
The scene point at the center of the view is used as the anchor.
QGraphicsView.ViewportAnchor.AnchorUnderMouse
The point under the mouse is used as the anchor.
See also
- class CacheModeFlag¶
(inherits
enum.Flag) This enum describes the flags that you can set for aQGraphicsView‘s cache mode.Constant
Description
QGraphicsView.CacheModeFlag.CacheNone
All painting is done directly onto the viewport.
QGraphicsView.CacheModeFlag.CacheBackground
The background is cached. This affects both custom backgrounds, and backgrounds based on the
backgroundBrushproperty. When this flag is enabled,QGraphicsViewwill allocate one pixmap with the full size of the viewport.See also
- class DragMode¶
This enum describes the default action for the view when pressing and dragging the mouse over the viewport.
Constant
Description
QGraphicsView.DragMode.NoDrag
Nothing happens; the mouse event is ignored.
QGraphicsView.DragMode.ScrollHandDrag
The cursor changes into a pointing hand, and dragging the mouse around will scroll the scrolbars. This mode works both in
interactiveand non-interactive mode.QGraphicsView.DragMode.RubberBandDrag
A rubber band will appear. Dragging the mouse will set the rubber band geometry, and all items covered by the rubber band are selected. This mode is disabled for non-interactive views.
See also
- class ViewportUpdateMode¶
This enum describes how
QGraphicsViewupdates its viewport when the scene contents change or are exposed.Constant
Description
QGraphicsView.ViewportUpdateMode.FullViewportUpdate
When any visible part of the scene changes or is reexposed,
QGraphicsViewwill update the entire viewport. This approach is fastest whenQGraphicsViewspends more time figuring out what to draw than it would spend drawing (e.g., when very many small items are repeatedly updated). This is the preferred update mode for viewports that do not support partial updates, such as QOpenGLWidget, and for viewports that need to disable scroll optimization.QGraphicsView.ViewportUpdateMode.MinimalViewportUpdate
QGraphicsViewwill determine the minimal viewport region that requires a redraw, minimizing the time spent drawing by avoiding a redraw of areas that have not changed. This isQGraphicsView‘s default mode. Although this approach provides the best performance in general, if there are many small visible changes on the scene,QGraphicsViewmight end up spending more time finding the minimal approach than it will spend drawing.QGraphicsView.ViewportUpdateMode.SmartViewportUpdate
QGraphicsViewwill attempt to find an optimal update mode by analyzing the areas that require a redraw.QGraphicsView.ViewportUpdateMode.BoundingRectViewportUpdate
The bounding rectangle of all changes in the viewport will be redrawn. This mode has the advantage that
QGraphicsViewsearches only one region for changes, minimizing time spent determining what needs redrawing. The disadvantage is that areas that have not changed also need to be redrawn.QGraphicsView.ViewportUpdateMode.NoViewportUpdate
QGraphicsViewwill never update its viewport when the scene changes; the user is expected to control all updates. This mode disables all (potentially slow) item visibility testing inQGraphicsView, and is suitable for scenes that either require a fixed frame rate, or where the viewport is otherwise updated externally.See also
- class OptimizationFlag¶
(inherits
enum.Flag) This enum describes flags that you can enable to improve rendering performance inQGraphicsView. By default, none of these flags are set. Note that setting a flag usually imposes a side effect, and this effect can vary between paint devices and platforms.Constant
Description
QGraphicsView.OptimizationFlag.DontSavePainterState
When rendering,
QGraphicsViewprotects the painter state (see QPainter::save()) when rendering the background or foreground, and when rendering each item. This allows you to leave the painter in an altered state (i.e., you can call QPainter::setPen() or QPainter::setBrush() without restoring the state after painting). However, if the items consistently do restore the state, you should enable this flag to preventQGraphicsViewfrom doing the same.QGraphicsView.OptimizationFlag.DontAdjustForAntialiasing
Disables
QGraphicsView‘s antialiasing auto-adjustment of exposed areas. Items that render antialiased lines on the boundaries of theirboundingRect()can end up rendering parts of the line outside. To prevent rendering artifacts,QGraphicsViewexpands all exposed regions by 2 pixels in all directions. If you enable this flag,QGraphicsViewwill no longer perform these adjustments, minimizing the areas that require redrawing, which improves performance. A common side effect is that items that do draw with antialiasing can leave painting traces behind on the scene as they are moved.QGraphicsView.OptimizationFlag.IndirectPainting
Since Qt 4.6, restore the old painting algorithm that calls QGraphicsView::drawItems() and QGraphicsScene::drawItems(). To be used only for compatibility with old code.
Note
Properties can be used directly when
from __feature__ import true_propertyis used or via accessor functions otherwise.- property alignmentᅟ: Combination of Qt.AlignmentFlag¶
This property holds the alignment of the scene in the view when the whole scene is visible..
If the whole scene is visible in the view, (i.e., there are no visible scroll bars,) the view’s alignment will decide where the scene will be rendered in the view. For example, if the alignment is Qt::AlignCenter, which is default, the scene will be centered in the view, and if the alignment is (Qt::AlignLeft | Qt::AlignTop), the scene will be rendered in the top-left corner of the view.
- Access functions:
This property holds the background brush of the scene..
This property sets the background brush for the scene in this view. It is used to override the scene’s own background, and defines the behavior of
drawBackground(). To provide custom background drawing for this view, you can reimplementdrawBackground()instead.By default, this property contains a brush with the Qt::NoBrush pattern.
See also
- Access functions:
- property cacheModeᅟ: Combination of QGraphicsView.CacheModeFlag¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This property holds which parts of the view are cached.
QGraphicsViewcan cache pre-rendered content in a QPixmap, which is then drawn onto the viewport. The purpose of such caching is to speed up the total rendering time for areas that are slow to render. Texture, gradient and alpha blended backgrounds, for example, can be notibly slow to render; especially with a transformed view. TheCacheBackgroundflag enables caching of the view’s background. For example:view = QGraphicsView() view.setBackgroundBrush(QImage(":/images/backgroundtile.png")) view.setCacheMode(QGraphicsView.CacheBackground)
The cache is invalidated every time the view is transformed. However, when scrolling, only partial invalidation is required.
By default, nothing is cached.
See also
- Access functions:
- property dragModeᅟ: QGraphicsView.DragMode¶
This property holds the behavior for dragging the mouse over the scene while the left mouse button is pressed..
This property defines what should happen when the user clicks on the scene background and drags the mouse (e.g., scrolling the viewport contents using a pointing hand cursor, or selecting multiple items with a rubber band). The default value,
NoDrag, does nothing.This behavior only affects mouse clicks that are not handled by any item. You can define a custom behavior by creating a subclass of
QGraphicsViewand reimplementingmouseMoveEvent().- Access functions:
This property holds the foreground brush of the scene..
This property sets the foreground brush for the scene in this view. It is used to override the scene’s own foreground, and defines the behavior of
drawForeground(). To provide custom foreground drawing for this view, you can reimplementdrawForeground()instead.By default, this property contains a brush with the Qt::NoBrush pattern.
See also
- Access functions:
- property interactiveᅟ: bool¶
This property holds whether the view allows scene interaction..
If enabled, this view is set to allow scene interaction. Otherwise, this view will not allow interaction, and any mouse or key events are ignored (i.e., it will act as a read-only view).
By default, this property is
true.- Access functions:
- property optimizationFlagsᅟ: Combination of QGraphicsView.OptimizationFlag¶
This property holds flags that can be used to tune
QGraphicsView‘s performance..QGraphicsViewuses clipping, extra bounding rect adjustments, and certain other aids to improve rendering quality and performance for the common case graphics scene. However, depending on the target platform, the scene, and the viewport in use, some of these operations can degrade performance.The effect varies from flag to flag; see the
OptimizationFlagsdocumentation for details.By default, no optimization flags are enabled.
See also
- Access functions:
- property renderHintsᅟ: Combination of QPainter.RenderHint¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This property holds the default render hints for the view.
These hints are used to initialize QPainter before each visible item is drawn. QPainter uses render hints to toggle rendering features such as antialiasing and smooth pixmap transformation.
QPainter::TextAntialiasing is enabled by default.
Example:
scene = QGraphicsScene() scene.addRect(QRectF(-10, -10, 20, 20)) view = QGraphicsView(scene) view.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.SmoothPixmapTransform) view.show()
- Access functions:
- property resizeAnchorᅟ: QGraphicsView.ViewportAnchor¶
This property holds how the view should position the scene when the view is resized..
QGraphicsViewuses this property to decide how to position the scene in the viewport when the viewport widget’s size changes. The default behavior,NoAnchor, leaves the scene’s position unchanged during a resize; the top-left corner of the view will appear to be anchored while resizing.Note that the effect of this property is noticeable when only a part of the scene is visible (i.e., when there are scroll bars). Otherwise, if the whole scene fits in the view,
QGraphicsSceneuses the view alignment to position the scene in the view.See also
- Access functions:
- property rubberBandSelectionModeᅟ: Qt.ItemSelectionMode¶
This property holds the behavior for selecting items with a rubber band selection rectangle..
This property defines how items are selected when using the
RubberBandDragdrag mode.The default value is Qt::IntersectsItemShape; all items whose shape intersects with or is contained by the rubber band are selected.
See also
- Access functions:
This property holds the area of the scene visualized by this view..
The scene rectangle defines the extent of the scene, and in the view’s case, this means the area of the scene that you can navigate using the scroll bars.
If unset, or if a null QRectF is set, this property has the same value as
sceneRect, and it changes withsceneRect. Otherwise, the view’s scene rect is unaffected by the scene.Note that, although the scene supports a virtually unlimited size, the range of the scroll bars will never exceed the range of an integer (INT_MIN, INT_MAX). When the scene is larger than the scroll bars’ values, you can choose to use
translate()to navigate the scene instead.By default, this property contains a rectangle at the origin with zero width and height.
See also
- Access functions:
- property transformationAnchorᅟ: QGraphicsView.ViewportAnchor¶
This property holds how the view should position the scene during transformations..
QGraphicsViewuses this property to decide how to position the scene in the viewport when the transformation matrix changes, and the coordinate system of the view is transformed. The default behavior,AnchorViewCenter, ensures that the scene point at the center of the view remains unchanged during transformations (e.g., when rotating, the scene will appear to rotate around the center of the view).Note that the effect of this property is noticeable when only a part of the scene is visible (i.e., when there are scroll bars). Otherwise, if the whole scene fits in the view,
QGraphicsSceneuses the view alignment to position the scene in the view.See also
- Access functions:
- property viewportUpdateModeᅟ: QGraphicsView.ViewportUpdateMode¶
This property holds how the viewport should update its contents..
QGraphicsViewuses this property to decide how to update areas of the scene that have been reexposed or changed. Usually you do not need to modify this property, but there are some cases where doing so can improve rendering performance. See theViewportUpdateModedocumentation for specific details.The default value is
MinimalViewportUpdate, whereQGraphicsViewwill update as small an area of the viewport as possible when the contents change.See also
- Access functions:
Constructs a
QGraphicsView.parentis passed toQWidget‘s constructor.- __init__(scene[, parent=None])
- Parameters:
scene –
QGraphicsSceneparent –
QWidget
Constructs a
QGraphicsViewand sets the visualized scene toscene.parentis passed toQWidget‘s constructor.- alignment()¶
- Return type:
Combination of
AlignmentFlag
See also
Getter of property
alignmentᅟ.- backgroundBrush()¶
- Return type:
See also
Getter of property
backgroundBrushᅟ.- cacheMode()¶
- Return type:
Combination of
CacheModeFlag
See also
Getter of property
cacheModeᅟ.- centerOn(item)¶
- Parameters:
item –
QGraphicsItem
This is an overloaded function.
Scrolls the contents of the viewport to ensure that
itemis centered in the view.See also
- centerOn(pos)
- Parameters:
pos –
QPointF
Scrolls the contents of the viewport to ensure that the scene coordinate
pos, is centered in the view.Because
posis a floating point coordinate, and the scroll bars operate on integer coordinates, the centering is only an approximation.Note
If the item is close to or outside the border, it will be visible in the view, but not centered.
See also
- centerOn(x, y)
- Parameters:
x – float
y – float
This is an overloaded function.
This function is provided for convenience. It’s equivalent to calling
centerOn(QPointF(x,y)).- dragMode()¶
- Return type:
See also
Getter of property
dragModeᅟ.Draws the background of the scene using
painter, before any items and the foreground are drawn. Reimplement this function to provide a custom background for this view.If all you want is to define a color, texture or gradient for the background, you can call
setBackgroundBrush()instead.All painting is done in scene coordinates.
rectis the exposed rectangle.The default implementation fills
rectusing the view’sbackgroundBrush. If no such brush is defined (the default), the scene’s drawBackground() function is called instead.See also
Draws the foreground of the scene using
painter, after the background and all items are drawn. Reimplement this function to provide a custom foreground for this view.If all you want is to define a color, texture or gradient for the foreground, you can call
setForegroundBrush()instead.All painting is done in scene coordinates.
rectis the exposed rectangle.The default implementation fills
rectusing the view’sforegroundBrush. If no such brush is defined (the default), the scene’s drawForeground() function is called instead.See also
- drawItems(painter, items, options)¶
- Parameters:
painter –
QPainteritems –
QGraphicsItem[]options –
QStyleOptionGraphicsItem[]
Draws the items
itemsin the scene usingpainter, after the background and before the foreground are drawn.numItemsis the number of items initemsand options inoptions.optionsis a list of styleoptions; one for each item. Reimplement this function to provide custom item drawing for this view.The default implementation calls the scene’s drawItems() function.
Since Qt 4.6, this function is not called anymore unless the
IndirectPaintingflag is given as an Optimization flag.See also
drawForeground()drawBackground()drawItems()- ensureVisible(item[, xmargin=50[, ymargin=50]])¶
- Parameters:
item –
QGraphicsItemxmargin – int
ymargin – int
This is an overloaded function.
Scrolls the contents of the viewport so that the center of item
itemis visible, with margins specified in pixels byxmarginandymargin. If the specified point cannot be reached, the contents are scrolled to the nearest valid position. The default value for both margins is 50 pixels.See also
- ensureVisible(rect[, xmargin=50[, ymargin=50]])
- Parameters:
rect –
QRectFxmargin – int
ymargin – int
Scrolls the contents of the viewport so that the scene rectangle
rectis visible, with margins specified in pixels byxmarginandymargin. If the specified rect cannot be reached, the contents are scrolled to the nearest valid position. The default value for both margins is 50 pixels.See also
- ensureVisible(x, y, w, h[, xmargin=50[, ymargin=50]])
- Parameters:
x – float
y – float
w – float
h – float
xmargin – int
ymargin – int
This is an overloaded function.
This function is provided for convenience. It’s equivalent to calling
ensureVisible(QRectF(x,y,w,h),xmargin,ymargin).- fitInView(item[, aspectRadioMode=Qt.IgnoreAspectRatio])¶
- Parameters:
item –
QGraphicsItemaspectRadioMode –
AspectRatioMode
This is an overloaded function.
Ensures that
itemfits tightly inside the view, scaling the view according toaspectRatioMode.See also
- fitInView(rect[, aspectRadioMode=Qt.IgnoreAspectRatio])
- Parameters:
rect –
QRectFaspectRadioMode –
AspectRatioMode
Scales the view matrix and scrolls the scroll bars to ensure that the scene rectangle
rectfits inside the viewport.rectmust be inside the scene rect; otherwise, fitInView() cannot guarantee that the whole rect is visible.This function keeps the view’s rotation, translation, or shear. The view is scaled according to
aspectRatioMode.rectwill be centered in the view if it does not fit tightly.It’s common to call fitInView() from inside a reimplementation of
resizeEvent(), to ensure that the whole scene, or parts of the scene, scales automatically to fit the new size of the viewport as the view is resized. Note though, that calling fitInView() from insideresizeEvent()can lead to unwanted resize recursion, if the new transformation toggles the automatic state of the scrollbars. You can toggle the scrollbar policies to always on or always off to prevent this (seehorizontalScrollBarPolicy()andverticalScrollBarPolicy()).If
rectis empty, or if the viewport is too small, this function will do nothing.See also
- fitInView(x, y, w, h[, aspectRadioMode=Qt.IgnoreAspectRatio])
- Parameters:
x – float
y – float
w – float
h – float
aspectRadioMode –
AspectRatioMode
This is an overloaded function.
This convenience function is equivalent to calling
fitInView(QRectF(x,y,w,h),aspectRatioMode).See also
- foregroundBrush()¶
- Return type:
See also
Getter of property
foregroundBrushᅟ.- invalidateScene([rect=QRectF()[, layers=QGraphicsScene.AllLayers]])¶
- Parameters:
rect –
QRectFlayers – Combination of
SceneLayer
Invalidates and schedules a redraw of
layersinsiderect.rectis in scene coordinates. Any cached content forlayersinsiderectis unconditionally invalidated and redrawn.You can call this function to notify
QGraphicsViewof changes to the background or the foreground of the scene. It is commonly used for scenes with tile-based backgrounds to notify changes whenQGraphicsViewhas enabled background caching.Note that
QGraphicsViewcurrently supports background caching only (seeCacheBackground). This function is equivalent to callingupdate()if any layer butBackgroundLayeris passed.See also
invalidate()update()- isInteractive()¶
- Return type:
bool
Getter of property
interactiveᅟ.- isTransformed()¶
- Return type:
bool
Returns
trueif the view is transformed (i.e., a non-identity transform has been assigned, or the scrollbars are adjusted).See also
setTransform()horizontalScrollBar()verticalScrollBar()Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns the item at position
pos, which is in viewport coordinates. If there are several items at this position, this function returns the topmost item.Example:
def mousePressEvent(self, event): if QGraphicsItem item = itemAt(event.pos()): print("You clicked on item", item) else: qDebug("You didn't click on an item.")
See also
items()Sorting- itemAt(x, y)
- Parameters:
x – int
y – int
- Return type:
This is an overloaded function.
This function is provided for convenience. It’s equivalent to calling
itemAt(QPoint(x,y)).- items()¶
- Return type:
.list of QGraphicsItem
Returns a list of all the items in the associated scene, in descending stacking order (i.e., the first item in the returned list is the uppermost item).
See also
items()Sorting- items(pos)
- Parameters:
pos –
QPoint- Return type:
.list of QGraphicsItem
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Returns a list of all the items at the position
posin the view. The items are listed in descending stacking order (i.e., the first item in the list is the uppermost item, and the last item is the lowermost item).posis in viewport coordinates.This function is most commonly called from within mouse event handlers in a subclass in
QGraphicsView.posis in untransformed viewport coordinates, just like QMouseEvent::pos().def mousePressEvent(self, event): print("There are", items(event.pos()).size()) << "items at position" << mapToScene(event.pos())
See also
items()Sorting- items(path[, mode=Qt.IntersectsItemShape])
- Parameters:
path –
QPainterPathmode –
ItemSelectionMode
- Return type:
.list of QGraphicsItem
This is an overloaded function.
Returns a list of all the items that, depending on
mode, are either contained by or intersect withpath.pathis in viewport coordinates.The default value for
modeis Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained bypathare returned.See also
itemAt()items()mapToScene()Sorting- items(polygon[, mode=Qt.IntersectsItemShape])
- Parameters:
polygon –
QPolygonmode –
ItemSelectionMode
- Return type:
.list of QGraphicsItem
This is an overloaded function.
Returns a list of all the items that, depending on
mode, are either contained by or intersect withpolygon.polygonis in viewport coordinates.The default value for
modeis Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained bypolygonare returned.The items are sorted by descending stacking order (i.e., the first item in the returned list is the uppermost item).
See also
itemAt()items()mapToScene()Sorting- items(rect[, mode=Qt.IntersectsItemShape])
- Parameters:
rect –
QRectmode –
ItemSelectionMode
- Return type:
.list of QGraphicsItem
This is an overloaded function.
Returns a list of all the items that, depending on
mode, are either contained by or intersect withrect.rectis in viewport coordinates.The default value for
modeis Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained byrectare returned.The items are sorted in descending stacking order (i.e., the first item in the returned list is the uppermost item).
See also
itemAt()items()mapToScene()Sorting- items(x, y)
- Parameters:
x – int
y – int
- Return type:
.list of QGraphicsItem
This function is provided for convenience. It’s equivalent to calling items(QPoint(
x,y)).- items(x, y, w, h[, mode=Qt.IntersectsItemShape])
- Parameters:
x – int
y – int
w – int
h – int
mode –
ItemSelectionMode
- Return type:
.list of QGraphicsItem
This convenience function is equivalent to calling items(QRectF(
x,y,w,h),mode).- mapFromScene(path)¶
- Parameters:
path –
QPainterPath- Return type:
Returns the scene coordinate painter path
pathto a viewport coordinate painter path.See also
Returns the scene coordinate
pointto viewport coordinates.See also
Returns the scene coordinate polygon
polygonto a viewport coordinate polygon.See also
Returns the scene rectangle
rectto a viewport coordinate polygon.See also
- mapFromScene(x, y)
- Parameters:
x – float
y – float
- Return type:
This function is provided for convenience. It’s equivalent to calling
mapFromScene(QPointF(x,y)).- mapFromScene(x, y, w, h)
- Parameters:
x – float
y – float
w – float
h – float
- Return type:
This function is provided for convenience. It’s equivalent to calling
mapFromScene(QRectF(x,y,w,h)).- mapToScene(path)¶
- Parameters:
path –
QPainterPath- Return type:
Returns the viewport painter path
pathmapped to a scene coordinate painter path.See also
Returns the viewport coordinate
pointmapped to scene coordinates.Note: It can be useful to map the whole rectangle covered by the pixel at
pointinstead of the point itself. To do this, you can callmapToScene(QRect(point, QSize(2, 2))).See also
Returns the viewport polygon
polygonmapped to a scene coordinate polygon.See also
Returns the viewport rectangle
rectmapped to a scene coordinate polygon.See also
- mapToScene(x, y)
- Parameters:
x – int
y – int
- Return type:
This function is provided for convenience. It’s equivalent to calling
mapToScene(QPoint(x,y)).- mapToScene(x, y, w, h)
- Parameters:
x – int
y – int
w – int
h – int
- Return type:
This function is provided for convenience. It’s equivalent to calling
mapToScene(QRect(x,y,w,h)).- optimizationFlags()¶
- Return type:
Combination of
OptimizationFlag
See also
Getter of property
optimizationFlagsᅟ.- render(painter[, target=QRectF()[, source=QRect()[, aspectRatioMode=Qt.KeepAspectRatio]]])¶
- Parameters:
painter –
QPaintertarget –
QRectFsource –
QRectaspectRatioMode –
AspectRatioMode
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Renders the
sourcerect, which is in view coordinates, from the scene intotarget, which is in paint device coordinates, usingpainter. This function is useful for capturing the contents of the view onto a paint device, such as a QImage (e.g., to take a screenshot), or for printing to QPrinter. For example:scene = QGraphicsScene() scene.addItem(... ... view = QGraphicsView(scene) view.show() ... printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) painter = QPainter(printer) # print, fitting the viewport contents into a full page view.render(painter) # print the upper half of the viewport into the lower. # half of the page. viewport = view.viewport().rect() view.render(painter, QRectF(0, printer.height() / 2, printer.width(), printer.height() / 2), viewport.adjusted(0, 0, 0, -viewport.height() / 2))
If
sourceis a null rect, this function will useviewport()->rect()to determine what to draw. Iftargetis a null rect, the full dimensions ofpainter's paint device (e.g., for a QPrinter, the page size) will be used.The source rect contents will be transformed according to
aspectRatioModeto fit into the target rect. By default, the aspect ratio is kept, andsourceis scaled to fit intarget.See also
- renderHints()¶
- Return type:
Combination of
RenderHint
See also
Getter of property
renderHintsᅟ.- resetCachedContent()¶
Resets any cached content. Calling this function will clear
QGraphicsView‘s cache. If the current cache mode isCacheNone, this function does nothing.This function is called automatically for you when the
backgroundBrushorbackgroundBrushproperties change; you only need to call this function if you have reimplementeddrawBackground()ordrawBackground()to draw a custom background, and need to trigger a full redraw.See also
- resetTransform()¶
Resets the view transformation to the identity matrix.
See also
- resizeAnchor()¶
- Return type:
See also
Getter of property
resizeAnchorᅟ.- rotate(angle)¶
- Parameters:
angle – float
Rotates the current view transformation
angledegrees clockwise.See also
- rubberBandChanged(viewportRect, fromScenePoint, toScenePoint)¶
This signal is emitted when the rubber band rect is changed. The viewport Rect is specified by
rubberBandRect. The drag start position and drag end position are provided in scene points withfromScenePointandtoScenePoint.When rubberband selection ends this signal will be emitted with null vales.
See also
This functions returns the current rubber band area (in viewport coordinates) if the user is currently doing an itemselection with rubber band. When the user is not using the rubber band this functions returns (a null) QRectF().
Notice that part of this QRect can be outside the visual viewport. It can e.g contain negative values.
- rubberBandSelectionMode()¶
- Return type:
See also
Getter of property
rubberBandSelectionModeᅟ.- scale(sx, sy)¶
- Parameters:
sx – float
sy – float
Scales the current view transformation by (
sx,sy).See also
- scene()¶
- Return type:
Returns a pointer to the scene that is currently visualized in the view. If no scene is currently visualized,
Noneis returned.See also
- sceneRect()¶
- Return type:
See also
Getter of property
sceneRectᅟ.- setAlignment(alignment)¶
- Parameters:
alignment – Combination of
AlignmentFlag
See also
Setter of property
alignmentᅟ.Setter of property
backgroundBrushᅟ.- setCacheMode(mode)¶
- Parameters:
mode – Combination of
CacheModeFlag
See also
Setter of property
cacheModeᅟ.Setter of property
dragModeᅟ.Setter of property
foregroundBrushᅟ.- setInteractive(allowed)¶
- Parameters:
allowed – bool
See also
Setter of property
interactiveᅟ.- setOptimizationFlag(flag[, enabled=true])¶
- Parameters:
flag –
OptimizationFlagenabled – bool
Enables
flagifenabledis true; otherwise disablesflag.See also
- setOptimizationFlags(flags)¶
- Parameters:
flags – Combination of
OptimizationFlag
See also
Setter of property
optimizationFlagsᅟ.- setRenderHint(hint[, enabled=true])¶
- Parameters:
hint –
RenderHintenabled – bool
If
enabledis true, the render hinthintis enabled; otherwise it is disabled.See also
- setRenderHints(hints)¶
- Parameters:
hints – Combination of
RenderHint
See also
Setter of property
renderHintsᅟ.- setResizeAnchor(anchor)¶
- Parameters:
anchor –
ViewportAnchor
See also
Setter of property
resizeAnchorᅟ.- setRubberBandSelectionMode(mode)¶
- Parameters:
mode –
ItemSelectionMode
See also
Setter of property
rubberBandSelectionModeᅟ.- setScene(scene)¶
- Parameters:
scene –
QGraphicsScene
Sets the current scene to
scene. Ifsceneis already being viewed, this function does nothing.When a scene is set on a view, the
changed()signal is automatically connected to this view’supdateScene()slot, and the view’s scroll bars are adjusted to fit the size of the scene.The view does not take ownership of
scene.See also
Setter of property
sceneRectᅟ.- setSceneRect(x, y, w, h)
- Parameters:
x – float
y – float
w – float
h – float
- setTransform(matrix[, combine=false])¶
- Parameters:
matrix –
QTransformcombine – bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Sets the view’s current transformation matrix to
matrix.If
combineis true, thenmatrixis combined with the current matrix; otherwise,matrixreplaces the current matrix.combineis false by default.The transformation matrix transforms the scene into view coordinates. Using the default transformation, provided by the identity matrix, one pixel in the view represents one unit in the scene (e.g., a 10x10 rectangular item is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is applied, the scene will be drawn in 1:2 (e.g., a 10x10 rectangular item is then drawn using 20x20 pixels in the view).
Example:
scene = QGraphicsScene() scene.addText("GraphicsView rotated clockwise") view = QGraphicsView(scene) view.rotate(90) # the text is rendered with a 90 degree clockwise rotation view.show()
To simplify interaction with items using a transformed view,
QGraphicsViewprovides mapTo… and mapFrom… functions that can translate between scene and view coordinates. For example, you can callmapToScene()to map a view coordinate to a floating point scene coordinate, ormapFromScene()to map from floating point scene coordinates to view coordinates.- setTransformationAnchor(anchor)¶
- Parameters:
anchor –
ViewportAnchor
See also
Setter of property
transformationAnchorᅟ.- setViewportUpdateMode(mode)¶
- Parameters:
mode –
ViewportUpdateMode
See also
Setter of property
viewportUpdateModeᅟ.- shear(sh, sv)¶
- Parameters:
sh – float
sv – float
Shears the current view transformation by (
sh,sv).See also
- transform()¶
- Return type:
Returns the current transformation matrix for the view. If no current transformation is set, the identity matrix is returned.
See also
- transformationAnchor()¶
- Return type:
See also
Getter of property
transformationAnchorᅟ.- translate(dx, dy)¶
- Parameters:
dx – float
dy – float
Translates the current view transformation by (
dx,dy).See also
- updateScene(rects)¶
- Parameters:
rects – .list of QRectF
Schedules an update of the scene rectangles
rects.See also
Notifies
QGraphicsViewthat the scene’s scene rect has changed.rectis the new scene rect. If the view already has an explicitly set scene rect, this function does nothing.See also
- viewportTransform()¶
- Return type:
Returns a matrix that maps scene coordinates to viewport coordinates.
See also
- viewportUpdateMode()¶
- Return type:
See also
Getter of property
viewportUpdateModeᅟ.