Qt Graphics View Framework: QGraphicsView

1. Description

QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable viewport. example:

QGraphicsScene scene;
scene.addText("Hello, world!");

QGraphicsView view(&scene);
view.show();

Views can be used to visualize the entire scene, or only a portion of it. By default, the visual area is automatically detected when the view is first shown (by calling QGraphicsScene::itemsBoundingRect()). To set the visual area rectangle yourself, you can call setSceneRect(). This will adjust the range of the scrollbar appropriately. Note that although the scene supports almost infinite sizes, the range of the scrollbar will not exceed the integer range (INT_MIN, INT_MAX).

Items in the scene can be interacted with using the mouse and keyboard. QGraphicsView converts mouse and button events into scene events and forwards them to the visualized scene.

Two, type members

1. QGraphicsView::CacheModeFlag: The cache mode of the view. Views can cache pre-rendered content in a QPixmap and then draw it to the viewport. The purpose of this caching is to speed up the overall render time in areas that render slowly. For example, textures, gradients, and alpha-blended backgrounds can be very slow to render, especially with transformed views. The cache is invalidated every time the view is transformed. When scrolling, only partial invalidation is required.

  • CacheNone: No caching, all drawing is done directly on the viewport.
  • CacheBackground: Enable cache background.

2. QGraphicsView::DragMode: The default operation of the view when pressing and dragging the mouse on the viewport.

  • NoDrag: No dragging, mouse events are ignored.
  • ScrollHandDrag: The cursor changes to a pointing hand, and dragging the mouse will scroll the scroll bar. This mode works in both interactive and non-interactive modes.

 

  • RubberBandDrag: A rubber band box will appear. Dragging the mouse will set the range of the rubber band frame, and all items covered by the rubber band will be selected. This mode is disabled for non-interactive views.

 

3. QGraphicsView::OptimizationFlag: A flag that can be enabled to improve view rendering performance. By default, these flags are not set. Setting flags often has side effects, and this effect may vary between drawing devices and platforms.

  • DontSavePainterState: When rendering, the view saves the painter state (QPainter::save()) when rendering the background or foreground and when rendering each graphical item.
  • DontAdjustForAntialiasing: Disables the view's automatic adjustment of antialiasing for exposed areas. Graphics items that render anti-aliased lines on QGraphicsItem::boundingRect() bounds may end up rendering partial lines on the outside. To prevent rendering artifacts, the view dilates all exposed areas by 2 pixels in all directions. If this flag is enabled, the view will no longer perform these adjustments, minimizing the area that needs to be redrawn, improving performance. A common side effect is that items drawn with antialiasing leave paint marks in the scene when they are moved.

4. QGraphicsView::ViewportAnchor: The anchor point that the view can use when the user resizes or converts the view.

  • NoAnchor: There is no anchor point, that is, the view keeps the position of the scene unchanged.
  • AnchorViewCenter: The scene point at the center of the view is used as the anchor.
  • AnchorUnderMouse: The point under the mouse is used as the anchor.

5. QGraphicsView::ViewportUpdateMode: How to update the viewport when the scene content changes.

  • FullViewportUpdate: The view will update the entire viewport when any visible part of the scene changes or is re-exposed. This is the preferred update mode for viewports that don't support partial updates (such as QOpenGLWidget ) and for viewports that need to disable scroll optimization.
  • MinimalViewportUpdate: The view will determine the smallest viewport area that needs to be redrawn, minimizing paint time by avoiding redrawing unchanged areas. This is the default mode for views. While this approach provides the best performance overall, if there are many small visible changes in the scene, the view may end up spending more time finding ways to minimize regions than drawing.
  • SmartViewportUpdate: The view will try to find the best update pattern by analyzing the areas that need to be redrawn.
  • BoundingRectViewportUpdate: will redraw the bounding rectangle of all changes in the viewport. The advantage of this pattern is that the view only searches for changes in one area, minimizing the time it takes to figure out what needs to be redrawn. The downside is that areas that haven't changed also need to be repainted.
  • NoViewportUpdate: The view will never update its viewport when the scene changes, the user should control all updates. This mode disables all (possibly slow) graphics item visibility testing in the view, and is suitable for scenarios that require a fixed frame rate or where the viewport is otherwise updated externally.

Three, attribute members

1、alignment : Qt::Alignment

This property maintains the alignment of the scene in view when the entire scene is visible (ie no scrollbars are visible (view extent >= scene extent)). The alignment will determine where the scene will be rendered in the viewport. For example, if the alignment is Qt::AlignCenter, which is the default, the scene will be centered in the view, and if the alignment is (Qt::AlignLeft | Qt::AlignTop), the scene will be rendered at the top - left corner of the view.

2、backgroundBrush : QBrush

This property holds the scene's background brush. It is used to overlay the background of the scene itself. To provide custom background drawing for a view, you can instead reimplement drawBackground(). The default is a brush in Qt::NoBrush mode.

3、cacheMode: CacheMode

Cache background mode. like:

QGraphicsView view;
view.setBackgroundBrush(QImage(":/images/backgroundtile.png"));
view.setCacheMode(QGraphicsView::CacheBackground);

4、dragMode : DragMode

5、foregroundBrush : QBrush

This property holds the scene's foreground brush. It is used to override the foreground of the scene itself. To provide custom foreground drawing for a view, you can instead reimplement drawForeground(). The default is a brush in Qt::NoBrush mode.

6、interactive : bool

Whether the view allows scene interaction. If enabled, this view will be set to allow scene interaction. Otherwise no interaction is allowed and any mouse or key events will be ignored (i.e. it will act as a read-only view). The default is true.

7、optimizationFlags : OptimizationFlags

8、renderHints : QPainter::RenderHints

These hints are used to initialize QPainter before drawing each visible graphics item. 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();

9、resizeAnchor : ViewportAnchor

How the view should position the scene when the view is resized.

10、rubberBandSelectionMode : Qt::ItemSelectionMode

Behavior of selecting graphic items using a rubberband selection rectangle. For specific values, see: Detailed explanation of the 42nd member function of QGraphicsScene.

11、sceneRect : QRectF

The area of ​​the scene that the view visualizes. If not set, or if an empty QRectF is set, this property has the same value as QGraphicsScene::sceneRect and changes with QGraphicsScene::sceneRect. Otherwise, the view's scene rectangle is not affected by the scene.

12、transformationAnchor : ViewportAnchor

How the view should position the scene during transitions.

13、viewportUpdateMode : ViewportUpdateMode

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

3. Member functions

1、void invalidateScene(const QRectF &rect = QRectF(), QGraphicsScene::SceneLayers layers = QGraphicsScene::AllLayers)

Invalidates the layers within the rectangle rect in the scene and schedules a redraw. Any cached contents of the layer within the rect will be unconditionally invalidated and repainted.

2、【信号】 void rubberBandChanged(QRect rubberBandRect, QPointF fromScenePoint, QPointF toScenePoint)

This signal is emitted when the rubber band rectangle changes. The rubber band rectangle is rubberBandRect. Parameter 2 and parameter 3 are the drag start position and drag end position, both of which are points in the scene. This signal will be emitted with a null value when the rubber band selection ends.

3、void updateScene(const QList<QRectF> &rects)

Immediately updates the scene rectangle.

4、void centerOn(const QPointF &pos)

Scroll the contents of the viewport to ensure that scene coordinates pos are centered in the viewport.

5、void centerOn(const QGraphicsItem *item)

Scrolls the contents of the viewport to ensure that the graphic item is centered in the view.

6、void drawBackground(QPainter *painter, const QRectF &rect)

The drawBackground() of the scene is called by default.

7、void drawForeground(QPainter *painter, const QRectF &rect)

The drawForeground() of the scene is called by default. Use viewport()->update() to refresh the content.

8、void ensureVisible(const QRectF &rect, int xmargin = 50, int ymargin = 50)

Scrolls the contents of the viewport to make the scene rectangle rect visible, with margins specified in pixels by xmargin and ymargin . If the specified rectangle cannot be reached, the content is scrolled to the nearest valid position.

 

9、void ensureVisible(const QGraphicsItem *item, int xmargin = 50, int ymargin = 50)

Scrolls the contents of the viewport to make graphical items visible. If the specified graphic item's position cannot be reached, the content is scrolled to the nearest valid position.

10、void fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio)

Scale the view matrix and scroll the scrollbars to ensure the scene rect fits the viewport. The rect must be within the scene rect, otherwise fitInView() cannot guarantee that the entire rectangle is visible. This function only scales and scrolls the scrollbar but maintains the view's rotation, translation or shearing. The view is scaled according to aspectRatioMode.

gphv->fitInView(QRect(0,0,300,300));

 

 

11、void fitInView(const QGraphicsItem *item, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio)

Make sure the item fits snugly in the view, scaling the view according to aspectRatioMode.

 

12、QGraphicsItem * itemAt(const QPoint &pos)

Returns the graphics item at position pos, where pos is in viewport coordinates. If there are multiple graphics items at this position, this function returns the topmost graphics item.

13、QList<QGraphicsItem *> items()

Returns a list of all graphics items in the associated scene, sorted in descending stack order.

14、QList<QGraphicsItem *> items(const QPoint &pos)

Returns a list of all graphics items at position pos in the view. Sort in descending stacking order. pos is in viewport coordinates.

15、QList<QGraphicsItem *> items(const QRect &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape)

A list of all items contained in or intersected by rect. rect in viewport coordinates. For the mode, see: QGraphicsScene explains the 42nd member function in detail. Items are sorted in stacked descending order.

16、QList<QGraphicsItem *> items(const QPolygon &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape)

overloaded functions.

17、QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape)

overloaded functions.

18、QPoint mapFromScene(const QPointF &point)

QPolygon mapFromScene(const QRectF &rect)
QPolygon mapFromScene(const QPolygonF &polygon)
QPainterPath mapFromScene(const QPainterPath &path)

Points, rectangles, polygons, and paths in scene coordinates are converted to points, polygons, and paths in viewport coordinates.

19、QPointF mapToScene(const QPoint &point)

QPolygonF mapToScene(const QRect &rect)
QPolygonF mapToScene(const QPolygon &polygon)
QPainterPath mapToScene(const QPainterPath &path)

Convert view coordinates to scene coordinates.

20、void render(QPainter *painter, const QRectF &target = QRectF(), const QRect &source = QRect(), Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio)

Use the painter to render a source in view coordinates from the scene to a target in drawing device coordinates. If source is an empty rectangle, this function will use viewport()->rect() to determine what to draw. If the target is an empty rectangle, the full size of the device (e.g., for a QPrinter, the page size) will be drawn using the painter. The source rectangle content will be transformed to fit the destination rectangle according to aspectRatioMode. By default, the aspect ratio is maintained and the source is scaled to fit the destination.

This function can be used to capture the contents of the view onto a drawing device such as a QImage (for example, to take a screenshot) or to print to a QPrinter. For example:

QGraphicsScene scene;
scene.addItem(...
...

QGraphicsView view(&scene);
view.show();
...

QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
QPainter painter(&printer);

view.render(&painter);

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));

21、void resetCachedContent()

Reset all cached content. Calling this function will clear the view's cache.

If the current cache mode is CacheNone, this function does nothing. This function is called automatically when the backgroundBrush or QGraphicsScene::backgroundBrush property changes. You only need to call this function if you reimplement QGraphicsScene::drawBackground() or drawBackground() to draw a custom background and need to trigger a full redraw.

22、void resetTransform()

Reset the view transform to the identity matrix.

23、void rotate(qreal angle)

Rotates the current view clockwise.

24、QRect rubberBandRect()

If the rubber band is currently being used for item selection, this function returns the current rubber band area (in viewport coordinates). When the user is not using the rubber band, this function returns a (null) QRectF(). Part of this QRect may extend beyond the visual viewport, and it may contain negative values.

25、void scale(qreal sx, qreal sy)

Zoom the current view by (sx, sy).

26、void setTransform(const QTransform &matrix, bool combine = false)

Sets the transformation matrix for the view. For parameter 2, see the 46th function of QPainter's detailed explanation.

27、void shear(qreal sh, qreal sv)

Cut the current view transition via (sh, sv). See the 22nd function of QTransform for the clipping effect.

 

28、void translate(qreal dx, qreal dy)

Convert the current view transform to (dx, dy).

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Original link: https://blog.csdn.net/kenfan1647/article/details/117383803

Guess you like

Origin blog.csdn.net/hw5230/article/details/131872639