
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQGraphicsView class provides a widget for displaying the contents of aQGraphicsScene.More...
| Header: | #include <QGraphicsView> |
| Since: | Qt 4.2 |
| Inherits: | QAbstractScrollArea |
| Inherited By: |
| flags | CacheMode |
| enum | CacheModeFlag { CacheNone, CacheBackground } |
| enum | DragMode { NoDrag, ScrollHandDrag, RubberBandDrag } |
| enum | OptimizationFlag { DontClipPainter, DontSavePainterState, DontAdjustForAntialiasing, IndirectPainting } |
| flags | OptimizationFlags |
| enum | ViewportAnchor { NoAnchor, AnchorViewCenter, AnchorUnderMouse } |
| enum | ViewportUpdateMode { FullViewportUpdate, MinimalViewportUpdate, SmartViewportUpdate, BoundingRectViewportUpdate, NoViewportUpdate } |
|
|
| QGraphicsView(QWidget * parent = 0) | |
| QGraphicsView(QGraphicsScene * scene, QWidget * parent = 0) | |
| ~QGraphicsView() | |
| Qt::Alignment | alignment() const |
| QBrush | backgroundBrush() const |
| CacheMode | cacheMode() const |
| void | centerOn(const QPointF & pos) |
| void | centerOn(qreal x, qreal y) |
| void | centerOn(const QGraphicsItem * item) |
| DragMode | dragMode() const |
| void | ensureVisible(const QRectF & rect, int xmargin = 50, int ymargin = 50) |
| void | ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50) |
| void | ensureVisible(const QGraphicsItem * item, int xmargin = 50, int ymargin = 50) |
| void | fitInView(const QRectF & rect, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio) |
| void | fitInView(qreal x, qreal y, qreal w, qreal h, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio) |
| void | fitInView(const QGraphicsItem * item, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio) |
| QBrush | foregroundBrush() const |
| bool | isInteractive() const |
| bool | isTransformed() const |
| QGraphicsItem * | itemAt(const QPoint & pos) const |
| QGraphicsItem * | itemAt(int x, int y) const |
| QList<QGraphicsItem *> | items() const |
| QList<QGraphicsItem *> | items(const QPoint & pos) const |
| QList<QGraphicsItem *> | items(int x, int y) const |
| QList<QGraphicsItem *> | items(int x, int y, int w, int h, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const |
| QList<QGraphicsItem *> | items(const QRect & rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const |
| QList<QGraphicsItem *> | items(const QPolygon & polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const |
| QList<QGraphicsItem *> | items(const QPainterPath & path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const |
| QPoint | mapFromScene(const QPointF & point) const |
| QPolygon | mapFromScene(const QRectF & rect) const |
| QPolygon | mapFromScene(const QPolygonF & polygon) const |
| QPainterPath | mapFromScene(const QPainterPath & path) const |
| QPoint | mapFromScene(qreal x, qreal y) const |
| QPolygon | mapFromScene(qreal x, qreal y, qreal w, qreal h) const |
| QPointF | mapToScene(const QPoint & point) const |
| QPolygonF | mapToScene(const QRect & rect) const |
| QPolygonF | mapToScene(const QPolygon & polygon) const |
| QPainterPath | mapToScene(const QPainterPath & path) const |
| QPointF | mapToScene(int x, int y) const |
| QPolygonF | mapToScene(int x, int y, int w, int h) const |
| QMatrix | matrix() const |
| OptimizationFlags | optimizationFlags() const |
| void | render(QPainter * painter, const QRectF & target = QRectF(), const QRect & source = QRect(), Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio) |
| QPainter::RenderHints | renderHints() const |
| void | resetCachedContent() |
| void | resetMatrix() |
| void | resetTransform() |
| ViewportAnchor | resizeAnchor() const |
| void | rotate(qreal angle) |
| Qt::ItemSelectionMode | rubberBandSelectionMode() const |
| void | scale(qreal sx, qreal sy) |
| QGraphicsScene * | scene() const |
| QRectF | sceneRect() const |
| void | setAlignment(Qt::Alignment alignment) |
| void | setBackgroundBrush(const QBrush & brush) |
| void | setCacheMode(CacheMode mode) |
| void | setDragMode(DragMode mode) |
| void | setForegroundBrush(const QBrush & brush) |
| void | setInteractive(bool allowed) |
| void | setMatrix(const QMatrix & matrix, bool combine = false) |
| void | setOptimizationFlag(OptimizationFlag flag, bool enabled = true) |
| void | setOptimizationFlags(OptimizationFlags flags) |
| void | setRenderHint(QPainter::RenderHint hint, bool enabled = true) |
| void | setRenderHints(QPainter::RenderHints hints) |
| void | setResizeAnchor(ViewportAnchor anchor) |
| void | setRubberBandSelectionMode(Qt::ItemSelectionMode mode) |
| void | setScene(QGraphicsScene * scene) |
| void | setSceneRect(const QRectF & rect) |
| void | setSceneRect(qreal x, qreal y, qreal w, qreal h) |
| void | setTransform(const QTransform & matrix, bool combine = false) |
| void | setTransformationAnchor(ViewportAnchor anchor) |
| void | setViewportUpdateMode(ViewportUpdateMode mode) |
| void | shear(qreal sh, qreal sv) |
| QTransform | transform() const |
| ViewportAnchor | transformationAnchor() const |
| void | translate(qreal dx, qreal dy) |
| QTransform | viewportTransform() const |
| ViewportUpdateMode | viewportUpdateMode() const |
| virtual QVariant | inputMethodQuery(Qt::InputMethodQuery query) const |
| virtual QSize | sizeHint() const |
| void | invalidateScene(const QRectF & rect = QRectF(), QGraphicsScene::SceneLayers layers = QGraphicsScene::AllLayers) |
| void | updateScene(const QList<QRectF> & rects) |
| void | updateSceneRect(const QRectF & rect) |
| virtual void | drawBackground(QPainter * painter, const QRectF & rect) |
| virtual void | drawForeground(QPainter * painter, const QRectF & rect) |
| virtual void | contextMenuEvent(QContextMenuEvent * event) |
| virtual void | dragEnterEvent(QDragEnterEvent * event) |
| virtual void | dragLeaveEvent(QDragLeaveEvent * event) |
| virtual void | dragMoveEvent(QDragMoveEvent * event) |
| virtual void | dropEvent(QDropEvent * event) |
| virtual bool | event(QEvent * event) |
| virtual void | focusInEvent(QFocusEvent * event) |
| virtual bool | focusNextPrevChild(bool next) |
| virtual void | focusOutEvent(QFocusEvent * event) |
| virtual void | inputMethodEvent(QInputMethodEvent * event) |
| virtual void | keyPressEvent(QKeyEvent * event) |
| virtual void | keyReleaseEvent(QKeyEvent * event) |
| virtual void | mouseDoubleClickEvent(QMouseEvent * event) |
| virtual void | mouseMoveEvent(QMouseEvent * event) |
| virtual void | mousePressEvent(QMouseEvent * event) |
| virtual void | mouseReleaseEvent(QMouseEvent * event) |
| virtual void | paintEvent(QPaintEvent * event) |
| virtual void | resizeEvent(QResizeEvent * event) |
| virtual void | scrollContentsBy(int dx, int dy) |
| virtual void | showEvent(QShowEvent * event) |
| virtual bool | viewportEvent(QEvent * event) |
| virtual void | wheelEvent(QWheelEvent * event) |
| void | setupViewport(QWidget * widget) |
TheQGraphicsView class provides a widget for displaying the contents of aQGraphicsScene.
QGraphicsView visualizes the contents of aQGraphicsScene in a scrollable viewport. To create a scene with geometrical items, seeQGraphicsScene's documentation.QGraphicsView is part of theGraphics View Framework.
To visualize a scene, you start by constructing aQGraphicsView object, 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:
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 callingcenterOn(). By passing a point tocenterOn(),QGraphicsView will scroll its viewport to ensure that the point is centered in the view. An overload is provided for scrolling to aQGraphicsItem, in which caseQGraphicsView 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 callensureVisible() 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 callingQGraphicsScene::itemsBoundingRect()). 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).
QGraphicsView visualizes the scene by callingrender(). By default, the items are drawn onto the viewport by using a regularQPainter, and using default render hints. To change the default render hints thatQGraphicsView passes toQPainter when painting items, you can callsetRenderHints().
By default,QGraphicsView provides a regularQWidget for the viewport widget. You can access this widget by callingviewport(), or you can replace it by callingsetViewport(). To render usingOpenGL, simply callsetViewport(newQGLWidget).QGraphicsView takes ownership of the viewport widget.
QGraphicsView supports affine transformations, usingQTransform. 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.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 intoscene 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. Similiary, 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 ofQGraphicsView, and reimplementing the mouse and key event handlers. To simplify how you programmatically interact with items in the view,QGraphicsView provides 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.

See alsoQGraphicsScene,QGraphicsItem, andQGraphicsSceneEvent.
This enum describes the flags that you can set for aQGraphicsView'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 thebackgroundBrush property. When this flag is enabled,QGraphicsView will allocate one pixmap with the full size of the viewport. |
The CacheMode type is a typedef forQFlags<CacheModeFlag>. It stores an OR combination of CacheModeFlag values.
See alsocacheMode.
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 ininteractive 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 alsodragMode andQGraphicsScene::setSelectionArea().
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 | Value | Description |
|---|---|---|
QGraphicsView::DontClipPainter | 0x1 | This value is obsolete and has no effect. |
QGraphicsView::DontSavePainterState | 0x2 | When rendering,QGraphicsView protects the painter state (seeQPainter::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 callQPainter::setPen() orQPainter::setBrush() without restoring the state after painting). However, if the items consistently do restore the state, you should enable this flag to preventQGraphicsView from doing the same. |
QGraphicsView::DontAdjustForAntialiasing | 0x4 | DisablesQGraphicsView's antialiasing auto-adjustment of exposed areas. Items that render antialiased lines on the boundaries of theirQGraphicsItem::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.
The OptimizationFlags type is a typedef forQFlags<OptimizationFlag>. It stores an OR combination of OptimizationFlag values.
This enums describe the possible anchors thatQGraphicsView 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 alsoresizeAnchor andtransformationAnchor.
This enum describes howQGraphicsView 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 whenQGraphicsView 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 asQGLWidget, 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 isQGraphicsView'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 thatQGraphicsView 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 inQGraphicsView, 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 alsoviewportUpdateMode.
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 isQt::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) |
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 ofdrawBackground(). To provide custom background drawing for this view, you can reimplementdrawBackground() instead.
By default, this property contains a brush with theQt::NoBrush pattern.
Access functions:
| QBrush | backgroundBrush() const |
| void | setBackgroundBrush(const QBrush & brush) |
See alsoQGraphicsScene::backgroundBrush andforegroundBrush.
This property holds which parts of the view are cached.
QGraphicsView can cache pre-rendered content in aQPixmap, 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. TheCacheBackground 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:
| CacheMode | cacheMode() const |
| void | setCacheMode(CacheMode mode) |
See alsoresetCachedContent() andQPixmapCache.
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 ofQGraphicsView and reimplementingmouseMoveEvent().
Access functions:
| DragMode | dragMode() const |
| void | setDragMode(DragMode mode) |
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 ofdrawForeground(). To provide custom foreground drawing for this view, you can reimplementdrawForeground() instead.
By default, this property contains a brush with theQt::NoBrush pattern.
Access functions:
| QBrush | foregroundBrush() const |
| void | setForegroundBrush(const QBrush & brush) |
See alsoQGraphicsScene::foregroundBrush andbackgroundBrush.
This property holds whether the view allowed 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) |
This property holds 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 theOptimizationFlags documentation for details.
By default, no optimization flags are enabled.
This property was introduced in Qt 4.3.
Access functions:
| OptimizationFlags | optimizationFlags() const |
| void | setOptimizationFlags(OptimizationFlags flags) |
See alsosetOptimizationFlag().
This property holds the default render hints for the view.
These hints are used to initializeQPainter 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) |
This property holds 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 viewalignment to position the scene in the view.
Access functions:
| ViewportAnchor | resizeAnchor() const |
| void | setResizeAnchor(ViewportAnchor anchor) |
See alsoalignment,transformationAnchor, andQt::WNorthWestGravity.
This property holds the behavior for selecting items with a rubber band selection rectangle.
This property defines how items are selected when using theRubberBandDrag drag mode.
The default value isQt::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) |
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 nullQRectF is set, this property has the same value asQGraphicsScene::sceneRect, and it changes withQGraphicsScene::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 usetranslate() 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 alsoQGraphicsScene::sceneRect.
This property holds 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 viewalignment to position the scene in the view.
Access functions:
| ViewportAnchor | transformationAnchor() const |
| void | setTransformationAnchor(ViewportAnchor anchor) |
See alsoalignment andresizeAnchor.
This property holds 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 theViewportUpdateMode documentation for specific details.
The default value isMinimalViewportUpdate, whereQGraphicsView 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:
| ViewportUpdateMode | viewportUpdateMode() const |
| void | setViewportUpdateMode(ViewportUpdateMode mode) |
See alsoViewportUpdateMode andcacheMode.
Constructs aQGraphicsView.parent is passed toQWidget's constructor.
Constructs aQGraphicsView and sets the visualized scene toscene.parent is passed toQWidget's constructor.
Destructs theQGraphicsView object.
Scrolls the contents of the viewport to ensure that the scene coordinatepos, is centered in the view.
Becausepos is 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 alsoensureVisible().
This is an overloaded function.
This function is provided for convenience. It's equivalent to callingcenterOn(QPointF(x,y)).
This is an overloaded function.
Scrolls the contents of the viewport to ensure thatitem is centered in the view.
See alsoensureVisible().
[virtual protected]void QGraphicsView::contextMenuEvent(QContextMenuEvent * event)Reimplemented fromQWidget::contextMenuEvent().
[virtual protected]void QGraphicsView::dragEnterEvent(QDragEnterEvent * event)Reimplemented fromQWidget::dragEnterEvent().
[virtual protected]void QGraphicsView::dragLeaveEvent(QDragLeaveEvent * event)Reimplemented fromQWidget::dragLeaveEvent().
[virtual protected]void QGraphicsView::dragMoveEvent(QDragMoveEvent * event)Reimplemented fromQWidget::dragMoveEvent().
[virtual protected]void QGraphicsView::drawBackground(QPainter * painter, constQRectF & rect)Draws the background of the scene usingpainter, 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 callsetBackgroundBrush() instead.
All painting is done inscene coordinates.rect is the exposed rectangle.
The default implementation fillsrect using the view'sbackgroundBrush. If no such brush is defined (the default), the scene's drawBackground() function is called instead.
See alsodrawForeground() andQGraphicsScene::drawBackground().
[virtual protected]void QGraphicsView::drawForeground(QPainter * painter, constQRectF & rect)Draws the foreground of the scene usingpainter, 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 callsetForegroundBrush() instead.
All painting is done inscene coordinates.rect is the exposed rectangle.
The default implementation fillsrect using the view'sforegroundBrush. If no such brush is defined (the default), the scene's drawForeground() function is called instead.
See alsodrawBackground() andQGraphicsScene::drawForeground().
[virtual protected]void QGraphicsView::dropEvent(QDropEvent * event)Reimplemented fromQWidget::dropEvent().
Scrolls the contents of the viewport so that the scene rectanglerect is visible, with margins specified in pixels byxmargin andymargin. 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 alsocenterOn().
This is an overloaded function.
This function is provided for convenience. It's equivalent to callingensureVisible(QRectF(x,y,w,h),xmargin,ymargin).
This is an overloaded function.
Scrolls the contents of the viewport so that the center of itemitem is visible, with margins specified in pixels byxmargin andymargin. 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 alsocenterOn().
[virtual protected]bool QGraphicsView::event(QEvent * event)Reimplemented fromQObject::event().
Scales the view matrix and scrolls the scroll bars to ensure that the scene rectanglerect fits inside the viewport.rect must 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 toaspectRatioMode.rect will be centered in the view if it does not fit tightly.
It's common to call fitInView() from inside a reimplementation ofresizeEvent(), 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()).
Ifrect is empty, or if the viewport is too small, this function will do nothing.
See alsosetTransform(),ensureVisible(), andcenterOn().
This is an overloaded function.
This convenience function is equivalent to callingfitInView(QRectF(x,y,w,h),aspectRatioMode).
See alsoensureVisible() andcenterOn().
This is an overloaded function.
Ensures thatitem fits tightly inside the view, scaling the view according toaspectRatioMode.
See alsoensureVisible() andcenterOn().
[virtual protected]void QGraphicsView::focusInEvent(QFocusEvent * event)Reimplemented fromQWidget::focusInEvent().
[virtual protected]bool QGraphicsView::focusNextPrevChild(bool next)Reimplemented fromQWidget::focusNextPrevChild().
[virtual protected]void QGraphicsView::focusOutEvent(QFocusEvent * event)Reimplemented fromQWidget::focusOutEvent().
[virtual protected]void QGraphicsView::inputMethodEvent(QInputMethodEvent * event)Reimplemented fromQWidget::inputMethodEvent().
[virtual]QVariant QGraphicsView::inputMethodQuery(Qt::InputMethodQuery query) constReimplemented fromQWidget::inputMethodQuery().
[slot]void QGraphicsView::invalidateScene(constQRectF & rect = QRectF(),QGraphicsScene::SceneLayers layers = QGraphicsScene::AllLayers)Invalidates and schedules a redraw oflayers insiderect.rect is in scene coordinates. Any cached content forlayers insiderect is unconditionally invalidated and redrawn.
You can call this function to notifyQGraphicsView of changes to the background or the foreground of the scene. It is commonly used for scenes with tile-based backgrounds to notify changes whenQGraphicsView has enabled background caching.
Note thatQGraphicsView currently supports background caching only (seeQGraphicsView::CacheBackground). This function is equivalent to callingupdate() if any layer butQGraphicsScene::BackgroundLayer is passed.
See alsoQGraphicsScene::invalidate() andupdate().
Returns true if the view is transformed (i.e., a non-identity transform has been assigned, or the scrollbars are adjusted).
This function was introduced in Qt 4.6.
See alsosetTransform(),horizontalScrollBar(), andverticalScrollBar().
Returns the item at positionpos, which is in viewport coordinates. If there are several items at this position, this function returns the topmost item.
Example:
void CustomView::mousePressEvent(QMouseEvent*event){if (QGraphicsItem*item= itemAt(event->pos())) {qDebug()<<"You clicked on item"<< item; }else {qDebug()<<"You didn't click on an item."; }}
This is an overloaded function.
This function is provided for convenience. It's equivalent to callingitemAt(QPoint(x,y)).
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 alsoQGraphicsScene::items() andSorting.
Returns a list of all the items at the positionpos in 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).pos is in viewport coordinates.
This function is most commonly called from within mouse event handlers in a subclass inQGraphicsView.pos is in untransformed viewport coordinates, just likeQMouseEvent::pos().
void CustomView::mousePressEvent(QMouseEvent*event){qDebug()<<"There are"<< items(event->pos()).size()<<"items at position"<< mapToScene(event->pos());}
See alsoQGraphicsScene::items() andSorting.
This function is provided for convenience. It's equivalent to calling items(QPoint(x,y)).
This convenience function is equivalent to calling items(QRectF(x,y,w,h),mode).
This function was introduced in Qt 4.3.
This is an overloaded function.
Returns a list of all the items that, depending onmode, are either contained by or intersect withrect.rect is in viewport coordinates.
The default value formode isQt::IntersectsItemShape; all items whose exact shape intersects with or is contained byrect are returned.
The items are sorted in descending stacking order (i.e., the first item in the returned list is the uppermost item).
See alsoitemAt(),items(),mapToScene(), andSorting.
This is an overloaded function.
Returns a list of all the items that, depending onmode, are either contained by or intersect withpolygon.polygon is in viewport coordinates.
The default value formode isQt::IntersectsItemShape; all items whose exact shape intersects with or is contained bypolygon are returned.
The items are sorted by descending stacking order (i.e., the first item in the returned list is the uppermost item).
See alsoitemAt(),items(),mapToScene(), andSorting.
This is an overloaded function.
Returns a list of all the items that, depending onmode, are either contained by or intersect withpath.path is in viewport coordinates.
The default value formode isQt::IntersectsItemShape; all items whose exact shape intersects with or is contained bypath are returned.
See alsoitemAt(),items(),mapToScene(), andSorting.
[virtual protected]void QGraphicsView::keyPressEvent(QKeyEvent * event)Reimplemented fromQWidget::keyPressEvent().
[virtual protected]void QGraphicsView::keyReleaseEvent(QKeyEvent * event)Reimplemented fromQWidget::keyReleaseEvent().
Returns the scene coordinatepoint to viewport coordinates.
See alsomapToScene().
Returns the scene rectanglerect to a viewport coordinate polygon.
See alsomapToScene().
Returns the scene coordinate polygonpolygon to a viewport coordinate polygon.
See alsomapToScene().
Returns the scene coordinate painter pathpath to a viewport coordinate painter path.
See alsomapToScene().
This function is provided for convenience. It's equivalent to callingmapFromScene(QPointF(x,y)).
This function is provided for convenience. It's equivalent to callingmapFromScene(QRectF(x,y,w,h)).
Returns the viewport coordinatepoint mapped to scene coordinates.
Note: It can be useful to map the whole rectangle covered by the pixel atpoint instead of the point itself. To do this, you can call mapToScene(QRect(point,QSize(2, 2))).
See alsomapFromScene().
Returns the viewport rectanglerect mapped to a scene coordinate polygon.
See alsomapFromScene().
Returns the viewport polygonpolygon mapped to a scene coordinate polygon.
See alsomapFromScene().
Returns the viewport painter pathpath mapped to a scene coordinate painter path.
See alsomapFromScene().
This function is provided for convenience. It's equivalent to callingmapToScene(QPoint(x,y)).
This function is provided for convenience. It's equivalent to callingmapToScene(QRect(x,y,w,h)).
Returns the current transformation matrix for the view. If no current transformation is set, the identity matrix is returned.
See alsosetMatrix(),transform(),rotate(),scale(),shear(), andtranslate().
[virtual protected]void QGraphicsView::mouseDoubleClickEvent(QMouseEvent * event)Reimplemented fromQWidget::mouseDoubleClickEvent().
[virtual protected]void QGraphicsView::mouseMoveEvent(QMouseEvent * event)Reimplemented fromQWidget::mouseMoveEvent().
[virtual protected]void QGraphicsView::mousePressEvent(QMouseEvent * event)Reimplemented fromQWidget::mousePressEvent().
[virtual protected]void QGraphicsView::mouseReleaseEvent(QMouseEvent * event)Reimplemented fromQWidget::mouseReleaseEvent().
[virtual protected]void QGraphicsView::paintEvent(QPaintEvent * event)Reimplemented fromQWidget::paintEvent().
Renders thesource rect, 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 aQImage (e.g., to take a screenshot), or for printing toQPrinter. For example:
QGraphicsScene scene;scene.addItem(......QGraphicsView view(&scene);view.show();...QPrinter printer(QPrinter::HighResolution);printer.setPageSize(QPrinter::A4);QPainter painter(&printer);// print, fitting the viewport contents into a full pageview.render(&painter);// print the upper half of the viewport into the lower.// half of the page.QRect 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));
Ifsource is a null rect, this function will useviewport()->rect() to determine what to draw. Iftarget is a null rect, the full dimensions ofpainter's paint device (e.g., for aQPrinter, the page size) will be used.
The source rect contents will be transformed according toaspectRatioMode to fit into the target rect. By default, the aspect ratio is kept, andsource is scaled to fit intarget.
See alsoQGraphicsScene::render().
Resets any cached content. Calling this function will clearQGraphicsView's cache. If the current cache mode isCacheNone, this function does nothing.
This function is called automatically for you when thebackgroundBrush orQGraphicsScene::backgroundBrush properties change; you only need to call this function if you have reimplementedQGraphicsScene::drawBackground() orQGraphicsView::drawBackground() to draw a custom background, and need to trigger a full redraw.
See alsocacheMode().
Resets the view transformation matrix to the identity matrix.
See alsoresetTransform().
Resets the view transformation to the identity matrix.
See alsotransform() andsetTransform().
[virtual protected]void QGraphicsView::resizeEvent(QResizeEvent * event)Reimplemented fromQWidget::resizeEvent().
Rotates the current view transformationangle degrees clockwise.
See alsosetTransform(),transform(),scale(),shear(), andtranslate().
Scales the current view transformation by (sx,sy).
See alsosetTransform(),transform(),rotate(),shear(), andtranslate().
Returns a pointer to the scene that is currently visualized in the view. If no scene is currently visualized, 0 is returned.
See alsosetScene().
[virtual protected]void QGraphicsView::scrollContentsBy(int dx,int dy)Reimplemented fromQAbstractScrollArea::scrollContentsBy().
Sets the view's current transformation matrix tomatrix.
Ifcombine is true, thenmatrix is combined with the current matrix; otherwise,matrixreplaces the current matrix.combine is false by default.
The transformation matrix tranforms 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:
QGraphicsScene scene;scene.addText("GraphicsView rotated clockwise");QGraphicsView view(&scene);view.rotate(90);// the text is rendered with a 90 degree clockwise rotationview.show();
To simplify interation with items using a transformed view,QGraphicsView providesmapTo... andmapFrom... 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.
See alsomatrix(),setTransform(),rotate(),scale(),shear(), andtranslate().
Enablesflag ifenabled is true; otherwise disablesflag.
See alsooptimizationFlags.
Ifenabled is true, the render hinthint is enabled; otherwise it is disabled.
See alsorenderHints.
Sets the current scene toscene. Ifscene is already being viewed, this function does nothing.
When a scene is set on a view, theQGraphicsScene::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.
See alsoscene().
Sets the view's current transformation matrix tomatrix.
Ifcombine is true, thenmatrix is combined with the current matrix; otherwise,matrixreplaces the current matrix.combine is false by default.
The transformation matrix tranforms 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:
QGraphicsScene scene;scene.addText("GraphicsView rotated clockwise");QGraphicsView view(&scene);view.rotate(90);// the text is rendered with a 90 degree clockwise rotationview.show();
To simplify interation with items using a transformed view,QGraphicsView providesmapTo... andmapFrom... functions that can translate between scene and view coordinates. For example, you can callmapToScene() to map a view coordiate to a floating point scene coordinate, ormapFromScene() to map from floating point scene coordinates to view coordinates.
See alsotransform(),rotate(),scale(),shear(), andtranslate().
[protected slot]void QGraphicsView::setupViewport(QWidget * widget)This slot is called byQAbstractScrollArea aftersetViewport() has been called. Reimplement this function in a subclass ofQGraphicsView to initialize the new viewportwidget before it is used.
See alsosetViewport().
Shears the current view transformation by (sh,sv).
See alsosetTransform(),transform(),rotate(),scale(), andtranslate().
[virtual protected]void QGraphicsView::showEvent(QShowEvent * event)Reimplemented fromQWidget::showEvent().
[virtual]QSize QGraphicsView::sizeHint() constReimplemented fromQWidget::sizeHint().
Returns the current transformation matrix for the view. If no current transformation is set, the identity matrix is returned.
See alsosetTransform(),rotate(),scale(),shear(), andtranslate().
Translates the current view transformation by (dx,dy).
See alsosetTransform(),transform(),rotate(), andshear().
[slot]void QGraphicsView::updateScene(constQList<QRectF> & rects)Schedules an update of the scene rectanglesrects.
See alsoQGraphicsScene::changed().
[slot]void QGraphicsView::updateSceneRect(constQRectF & rect)NotifiesQGraphicsView that the scene's scene rect has changed.rect is the new scene rect. If the view already has an explicitly set scene rect, this function does nothing.
See alsosceneRect andQGraphicsScene::sceneRectChanged().
[virtual protected]bool QGraphicsView::viewportEvent(QEvent * event)Reimplemented fromQAbstractScrollArea::viewportEvent().
Returns a matrix that maps viewport coordinates to scene coordinates.
See alsomapToScene() andmapFromScene().
[virtual protected]void QGraphicsView::wheelEvent(QWheelEvent * event)Reimplemented fromQWidget::wheelEvent().
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.