QGraphicsView Class
The QGraphicsView class provides a widget for displaying the contents of a QGraphicsScene. More...
| Header: | #include <QGraphicsView> |
| qmake: | QT += widgets |
| Since: | Qt 4.2 |
| Inherits: | QAbstractScrollArea |
This class was introduced in Qt 4.2.
Public Types
| enum | CacheModeFlag { CacheNone, CacheBackground } |
| enum | DragMode { NoDrag, ScrollHandDrag, RubberBandDrag } |
| enum | OptimizationFlag { DontClipPainter, DontSavePainterState, DontAdjustForAntialiasing, IndirectPainting } |
| enum | ViewportAnchor { NoAnchor, AnchorViewCenter, AnchorUnderMouse } |
| enum | ViewportUpdateMode { FullViewportUpdate, MinimalViewportUpdate, SmartViewportUpdate, BoundingRectViewportUpdate, NoViewportUpdate } |
Properties
|
|
Public Functions
| Qt::Alignment | alignment() const |
| QBrush | backgroundBrush() const |
| QGraphicsView::CacheMode | cacheMode() const |
| QGraphicsView::DragMode | dragMode() const |
| QBrush | foregroundBrush() const |
| bool | isInteractive() const |
| QGraphicsView::OptimizationFlags | optimizationFlags() const |
| QPainter::RenderHints | renderHints() const |
| QGraphicsView::ViewportAnchor | resizeAnchor() const |
| Qt::ItemSelectionMode | rubberBandSelectionMode() const |
| QRectF | sceneRect() const |
| void | setAlignment(Qt::Alignment alignment) |
| void | setBackgroundBrush(const QBrush &brush) |
| void | setCacheMode(QGraphicsView::CacheMode mode) |
| void | setDragMode(QGraphicsView::DragMode mode) |
| void | setForegroundBrush(const QBrush &brush) |
| void | setInteractive(bool allowed) |
| void | setOptimizationFlags(QGraphicsView::OptimizationFlags flags) |
| void | setRenderHints(QPainter::RenderHints hints) |
| void | setResizeAnchor(QGraphicsView::ViewportAnchor anchor) |
| void | setRubberBandSelectionMode(Qt::ItemSelectionMode mode) |
| void | setSceneRect(const QRectF &rect) |
| void | setSceneRect(qreal x, qreal y, qreal w, qreal h) |
| void | setTransformationAnchor(QGraphicsView::ViewportAnchor anchor) |
| void | setViewportUpdateMode(QGraphicsView::ViewportUpdateMode mode) |
| QGraphicsView::ViewportAnchor | transformationAnchor() const |
| QGraphicsView::ViewportUpdateMode | viewportUpdateMode() const |
Detailed Description
QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable viewport. To create a scene with geometrical items, see QGraphicsScene's documentation. QGraphicsView is part of the Graphics View Framework.
To visualize a scene, you start by constructing a QGraphicsView object, passing the address of the scene you want to visualize to QGraphicsView's constructor. Alternatively, you can call setScene() to set the scene at a later point. After you call show(), the view will by default scroll to the center of the scene and display any items that are visible at this point. For example:
QGraphicsScene scene; scene.addText("Hello, world!"); QGraphicsView view(&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 to centerOn(), QGraphicsView will scroll its viewport to ensure that the point is centered in the view. An overload is provided for scrolling to a QGraphicsItem, in which case QGraphicsView will 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 call ensureVisible() instead.
QGraphicsView can 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 calling QGraphicsScene::itemsBoundingRect()). To set the visualized area rectangle yourself, you can call setSceneRect(). 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).
QGraphicsView visualizes the scene by calling render(). 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 that QGraphicsView passes to QPainter when painting items, you can call setRenderHints().
By default, QGraphicsView provides a regular QWidget for the viewport widget. You can access this widget by calling viewport(), or you can replace it by calling setViewport(). To render using OpenGL, simply call setViewport(new QOpenGLWidget). QGraphicsView takes ownership of the viewport widget.
QGraphicsView supports affine transformations, using QTransform. You can either pass a matrix to setTransform(), or you can call one of the convenience functions rotate(), scale(), translate() or shear(). The most two common transformations are scaling, which is used to implement zooming, and rotation. QGraphicsView keeps the center of the view fixed during a transformation. Because of the scene alignment (setAligment()), translating the view will have no visual impact.
You can interact with the items on the scene by using the mouse and keyboard. QGraphicsView translates the mouse and key events into scene events, (events that inherit QGraphicsSceneEvent,), 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 calling setInteractive().
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, QGraphicsView provides the mapping functions mapToScene() and mapFromScene(), and the item accessors items() and itemAt(). 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.

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.
See also QGraphicsScene, QGraphicsItem, and QGraphicsSceneEvent.
Member Type Documentation
enum QGraphicsView::CacheModeFlag
This enum describes the flags that you can set for a QGraphicsView's cache mode.
| Constant | Value | Description |
|---|---|---|
QGraphicsView::CacheNone | 0x0 | All painting is done directly onto the viewport. |
QGraphicsView::CacheBackground | 0x1 | The background is cached. This affects both custom backgrounds, and backgrounds based on the backgroundBrush property. When this flag is enabled, QGraphicsView will allocate one pixmap with the full size of the viewport. |
See also cacheMode.
enum QGraphicsView::DragMode
This enum describes the default action for the view when pressing and dragging the mouse over the viewport.
| Constant | Value | Description |
|---|---|---|
QGraphicsView::NoDrag | 0 | Nothing happens; the mouse event is ignored. |
QGraphicsView::ScrollHandDrag | 1 | The cursor changes into a pointing hand, and dragging the mouse around will scroll the scrolbars. This mode works both in interactive and non-interactive mode. |
QGraphicsView::RubberBandDrag | 2 | 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 dragMode and QGraphicsScene::setSelectionArea().
enum QGraphicsView::OptimizationFlag
This enum describes flags that you can enable to improve rendering performance in QGraphicsView. 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 | Value | Description |
|---|---|---|
QGraphicsView::DontClipPainter | 0x1 | This value is obsolete and has no effect. |
QGraphicsView::DontSavePainterState | 0x2 | When rendering, QGraphicsView protects 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 prevent QGraphicsView from doing the same. |
QGraphicsView::DontAdjustForAntialiasing | 0x4 | Disables QGraphicsView's antialiasing auto-adjustment of exposed areas. Items that render antialiased lines on the boundaries of their QGraphicsItem::boundingRect() can end up rendering parts of the line outside. To prevent rendering artifacts, QGraphicsView expands all exposed regions by 2 pixels in all directions. If you enable this flag, QGraphicsView will 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::IndirectPainting | 0x8 | 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. |
This enum was introduced or modified in Qt 4.3.
enum QGraphicsView::ViewportAnchor
This enums describe the possible anchors that QGraphicsView can use when the user resizes the view or when the view is transformed.
| Constant | Value | Description |
|---|---|---|
QGraphicsView::NoAnchor | 0 | No anchor, i.e. the view leaves the scene's position unchanged. |
QGraphicsView::AnchorViewCenter | 1 | The scene point at the center of the view is used as the anchor. |
QGraphicsView::AnchorUnderMouse | 2 | The point under the mouse is used as the anchor. |
See also resizeAnchor and transformationAnchor.
enum QGraphicsView::ViewportUpdateMode
This enum describes how QGraphicsView updates its viewport when the scene contents change or are exposed.
| Constant | Value | Description |
|---|---|---|
QGraphicsView::FullViewportUpdate | 0 | When any visible part of the scene changes or is reexposed, QGraphicsView will update the entire viewport. This approach is fastest when QGraphicsView spends 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::MinimalViewportUpdate | 1 | QGraphicsView will 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 is QGraphicsView's default mode. Although this approach provides the best performance in general, if there are many small visible changes on the scene, QGraphicsView might end up spending more time finding the minimal approach than it will spend drawing. |
QGraphicsView::SmartViewportUpdate | 2 | QGraphicsView will attempt to find an optimal update mode by analyzing the areas that require a redraw. |
QGraphicsView::BoundingRectViewportUpdate | 4 | The bounding rectangle of all changes in the viewport will be redrawn. This mode has the advantage that QGraphicsView searches 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::NoViewportUpdate | 3 | QGraphicsView will 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 in QGraphicsView, and is suitable for scenes that either require a fixed frame rate, or where the viewport is otherwise updated externally. |
This enum was introduced or modified in Qt 4.3.
See also viewportUpdateMode.
Property Documentation
alignment : Qt::Alignment
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:
| Qt::Alignment | alignment() const |
| void | setAlignment(Qt::Alignment alignment) |
backgroundBrush : QBrush
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 reimplement drawBackground() instead.
By default, this property contains a brush with the Qt::NoBrush pattern.
Access functions:
| QBrush | backgroundBrush() const |
| void | setBackgroundBrush(const QBrush &brush) |
See also QGraphicsScene::backgroundBrush and foregroundBrush.
cacheMode : CacheMode
This property holds which parts of the view are cached
QGraphicsView can 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. The CacheBackground flag enables caching of the view's background. For example:
QGraphicsView view; 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.
Access functions:
| QGraphicsView::CacheMode | cacheMode() const |
| void | setCacheMode(QGraphicsView::CacheMode mode) |
See also resetCachedContent() and QPixmapCache.
dragMode : 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 QGraphicsView and reimplementing mouseMoveEvent().
Access functions:
| QGraphicsView::DragMode | dragMode() const |
| void | setDragMode(QGraphicsView::DragMode mode) |
foregroundBrush : QBrush
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 reimplement drawForeground() instead.
By default, this property contains a brush with the Qt::NoBrush pattern.
Access functions:
| QBrush | foregroundBrush() const |
| void | setForegroundBrush(const QBrush &brush) |
See also QGraphicsScene::foregroundBrush and backgroundBrush.
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:
| bool | isInteractive() const |
| void | setInteractive(bool allowed) |
optimizationFlags : OptimizationFlags
flags that can be used to tune QGraphicsView's performance.
QGraphicsView uses 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 OptimizationFlags documentation for details.
By default, no optimization flags are enabled.
This property was introduced in Qt 4.3.
Access functions:
| QGraphicsView::OptimizationFlags | optimizationFlags() const |
| void | setOptimizationFlags(QGraphicsView::OptimizationFlags flags) |
See also setOptimizationFlag().
renderHints : QPainter::RenderHints
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:
QGraphicsScene scene; scene.addRect(QRectF(-10, -10, 20, 20)); QGraphicsView view(&scene); view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); view.show();
Access functions:
| QPainter::RenderHints | renderHints() const |
| void | setRenderHints(QPainter::RenderHints hints) |
resizeAnchor : ViewportAnchor
how the view should position the scene when the view is resized.
QGraphicsView uses 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, QGraphicsScene uses the view alignment to position the scene in the view.
Access functions:
| QGraphicsView::ViewportAnchor | resizeAnchor() const |
| void | setResizeAnchor(QGraphicsView::ViewportAnchor anchor) |
See also alignment and transformationAnchor.
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 RubberBandDrag drag mode.
The default value is Qt::IntersectsItemShape; all items whose shape intersects with or is contained by the rubber band are selected.
This property was introduced in Qt 4.3.
Access functions:
| Qt::ItemSelectionMode | rubberBandSelectionMode() const |
| void | setRubberBandSelectionMode(Qt::ItemSelectionMode mode) |
See also dragMode, items(), and rubberBandRect().
sceneRect : QRectF
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 QGraphicsScene::sceneRect, and it changes with QGraphicsScene::sceneRect. 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.
Access functions:
| QRectF | sceneRect() const |
| void | setSceneRect(const QRectF &rect) |
| void | setSceneRect(qreal x, qreal y, qreal w, qreal h) |
See also QGraphicsScene::sceneRect.
transformationAnchor : ViewportAnchor
how the view should position the scene during transformations.
QGraphicsView uses 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, QGraphicsScene uses the view alignment to position the scene in the view.
Access functions:
| QGraphicsView::ViewportAnchor | transformationAnchor() const |
| void | setTransformationAnchor(QGraphicsView::ViewportAnchor anchor) |
See also alignment and resizeAnchor.
viewportUpdateMode : ViewportUpdateMode
how the viewport should update its contents.
QGraphicsView uses 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 the ViewportUpdateMode documentation for specific details.
The default value is MinimalViewportUpdate, where QGraphicsView will update as small an area of the viewport as possible when the contents change.
This property was introduced in Qt 4.3.
Access functions:
| QGraphicsView::ViewportUpdateMode | viewportUpdateMode() const |
| void | setViewportUpdateMode(QGraphicsView::ViewportUpdateMode mode) |
See also ViewportUpdateMode and cacheMode.