Qt Graphics View Framework: Detailed QGraphicsScene

1. Description

1. The scene provides a plane for managing a large number of 2D graphics items. This class acts as a container for graphical items. It is used with views to visualize graphical items on 2D surfaces.

2. The scene does not have its own visual appearance and is only responsible for managing graphical items.

3. One of the greatest strengths of a scene is its ability to locate graphical items quickly and efficiently. Even with millions of graphic items in the scene.

4. Another responsibility of the scene is to propagate events from the view. To send an event to the scene, construct an event that extends QEvent, and then send it using QApplication::sendEvent(). event() is responsible for dispatching events to individual graphics items.

Two, type members

1. QGraphicsScene::ItemIndexMethod: The indexing algorithm of the scene.

  • QGraphicsScene::BspTreeIndex: binary space partition tree algorithm. The order of magnitude of all graph item positioning algorithms is close to logarithmic complexity. Adding, moving and removing graph items is logarithmic. This approach works best for static scenes (that is, scenes where most graphical items don't move).
  • QGraphicsScene::NoIndex: Do not save graphics item index. Locating graphics items has linear complexity because all graphics items in the scene are searched. However, adding, moving and deleting graphic items is done in constant time. This approach is best suited for dynamic scenarios, where many graphical items are added, moved, or removed in succession.

2. QGraphicsScene::SceneLayer: This enumeration describes the rendering layer in the scene. When the scene is drawing its content, it will render each layer separately, in order. Each layer represents a logo.

Drawing order: background > graphics item > foreground.

  • QGraphicsScene::ItemLayer: Graphics item layer. All graphics items rendered by the scene by calling the virtual function drawItems() are in this layer. Graphic item layers are drawn after the background layer, but before the foreground layer.
  • QGraphicsScene::BackgroundLayer: Background layer. The scene renders the background of the scene in this layer by calling the virtual function drawBackground(). The first thing to draw is the background layer.
  • QGraphicsScene::ForegroundLayer: Foreground layer. The scene renders the foreground of the scene in this layer by calling the virtual function drawForeground(). The foreground layer is drawn last of all layers.
  • QGraphicsScene::AllLayers: All layers, this value represents the combination of all three layers.

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↓↓

Three, attribute members

1、backgroundBrush : QBrush

Background layer brush. For example it can set the background grid of the scene:

gphs->setBackgroundBrush(QBrush(QPixmap(":/background1.png")));

 

 

2、bspTreeDepth : int

The depth of the BSP index tree. This property has no effect when using QGraphicsScene::NoIndex.

Depth directly affects the performance and memory usage of the scene. The latter grows exponentially with the depth of the tree. With optimal tree depth, scenes can determine the position of graphic items instantly, even for scenes with thousands or millions of graphic items. This also greatly improves rendering performance.

By default, this value is 0, in which case Qt will guess a reasonable default depth based on the size, position and number of graphical items in the scene. However, if these parameters change frequently, you may experience slowdowns as the scene rescales depth internally. The depth of the tree can be fixed by setting this property, avoiding a potential slowdown.

3、focusOnTouch : bool

This property holds whether the graphic item received focus when it received a touch start event (mobile). The usual behavior is to only transfer focus when a graphical item is clicked.

4、font: QFont

The font of the scene. Changes have no effect on general graphics items, only on QWidgets embedded in QGraphicsWidget.

5、foregroundBrush : QBrush

Foreground brush. The foreground layer is in front of the graphics item layer, so the set foreground brush will block the graphics items.

gphs->setForegroundBrush(QColor(255, 0, 0, 127));

gphs->setForegroundBrush(QBrush(Qt::lightGray, Qt::CrossPattern));

 

 

6、minimumRenderSize : qreal

The minimum render size that must be drawn. When rendering the scene, any graphics item whose width or height is smaller than this value will not be rendered. The default value is 0. If not set, or set to 0 or a negative value, all graph items will always be rendered. Graphical items that are not drawn because they are too small are still returned by methods like items() and itemAt() and participate in collision detection and interaction.

7、palette : QPalette

The palette of the scene. Changes have no effect on general graphics items, only on QWidgets embedded in QGraphicsWidget.

8、sceneRect : QRectF

The bounding rectangle of the scene. The scene bounding rectangle defines the extent of the scene. It is mainly used by views to determine the default scrollable area of ​​a view, and mainly used by scenes to manage graphics item indexes. If not set or set to an invalid rectangle, SceneRect() will return the largest bounding rectangle of all graphics items in the scene since the scene was created (that is, the rectangle will grow when adding or moving graphics items in the scene, but never decrease) ).

9. stickyFocus: bool (practical)

Whether clicking on the scene background clears focus.

4. Member functions

1、void advance()

Call the QGraphicsItem::advance() function of all graphics items in the scene.

2、[信号] void changed(const QList<QRectF> ®ion)

A signal emitted when the scene content changes (this signal is sent for any change in the scene, and this signal is sent extremely frequently). The argument contains a list of scene rectangles indicating the changed area.

3、void clear()

Removes all graphics items from the scene. (remove and delete delete)

4、void clearSelection()

Clear the current selection state.

5、[信号] void focusItemChanged(QGraphicsItem *newFocusItem, QGraphicsItem *oldFocusItem, Qt::FocusReason reason)

Whenever focus changes in the scene (when an item gains or loses input focus (involving one graphics item), or when focus passes from one graphics item to another (involving two graphics items)), the scene will emit this signal. You can connect to this signal if you need to track when other graphics items get input focus.

oldFocusItem is a pointer to the graphics item that previously had focus, or nullptr if no graphics item had focus before the signal was emitted. newFocusItem is a pointer to the graphics item that gained input focus; returns nullptr if focus is lost. For parameter 3, see the 61st member function of QGraphicsItem.

6、bool focusNextPrevChild(bool next)

Finds a new QGraphicsWidget to give keyboard focus to the Tab and Shift+Tab keys, returning true if one can be found; otherwise, returns false. This function searches forward if next is true, otherwise it searches backward.

7、void invalidate(const QRectF &rect = QRectF(), QGraphicsScene::SceneLayers layers = AllLayers)

Invalidates the rect in the scene and redraws it. All cached content in the layer will be unconditionally invalidated and repainted.

8, [signal] void sceneRectChanged(const QRectF &rect)

This signal is emitted when the scene rectangle changes. The argument is the new scene rectangle.

9. [Signal] void selectionChanged()

This signal is emitted when the selection changes. selectedItems() can be called to get a new list of selected graphics items. The selection changes whenever a shape item is selected or deselected, a selection area is set, cleared, or otherwise changed, a preselected shape item is added to the scene, or a selected shape item is removed from the scene.

The scene emits this signal only once for a group selection operation.

10、void update(const QRectF &rect = QRectF())

Redraws the area in the parameter.

11、~QGraphicsScene()

destructor. Removes and removes all graphics items from the scene object before destroying the scene object. The scene object is removed from all associated views.

12、QGraphicsItem *activePanel()

Returns the currently active panel.

 

13、QGraphicsWidget *activeWindow()

Returns the currently active window.

14、void addItem(QGraphicsItem *item)

Adds or moves a graphic item and all its children to this scene. If the item is visible (ie QGraphicsItem::isVisible() returns true).

If the graphic item is already in another scene, it will first be removed from its old scene and then added to that scene as a top layer.

When a graphic item is added to the scene, the scene will send an ItemSceneChange notification to the graphic item.

If the graphic item is a panel, the scene is active, and there are no active panels in the scene, the graphic item will be activated.

15、void clearFocus()

Remove focus from the scene. If any graphics item has focus when this function is called, it will lose focus, and will regain focus again when the scene regains focus.

16、QList<QGraphicsItem *> collidingItems(const QGraphicsItem *item, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape)

Returns a list of all graphics items that collide with parameter 1. Collisions are determined by calling QGraphicsItem::collidesWithItem(). Collision detection is determined by mode. By default, all graphic items whose shape intersects the graphic item or is contained within the shape of the graphic item are returned.

17、QGraphicsItemGroup *createItemGroup(const QList<QGraphicsItem *> &items)

Groups all graphics items in the argument list into a new group and returns a pointer to that group.

18、void destroyItemGroup(QGraphicsItemGroup *group)

Removes the group from the scene. Graphical items in the group are moved to the group's parent.

19. void drawBackground(QPainter *painter, const QRectF &rect) (virtual function)

Draw the background layer of the scene. All drawing is done in scene coordinates. The rect parameter is the exposed rectangle.

 

20. void drawForeground(QPainter *painter, const QRectF &rect) (virtual function)

Draw the foreground layer of the scene. All drawing is done in scene coordinates. The rect parameter is the exposed rectangle.

21、QGraphicsItem *focusItem()

This function will return the currently focused item of the scene when the scene is active, or nullptr if there is currently no focus. When the scene is inactive, this function returns the graphics item that will receive input focus when the scene becomes active. When the scene receives key events, the focused item will receive keyboard input.

22、bool hasFocus()

Whether the scene has focus. If the scene has focus, it will forward key events from QKeyEvent to the focused graphic item.

23、qreal height() / qreal width()

The width/height of sceneRect().

24、QVariant inputMethodQuery(Qt::InputMethodQuery query)

The input method uses this method to query a set of properties of the scene so that it can support complex input method operations.

25、bool isActive()

Returns true if the scene is active (for example, at least one QGraphicsView is active), false otherwise.

26、QGraphicsItem *itemAt(const QPointF &position, const QTransform &deviceTransform)

Returns the topmost visible item at the specified position, or nullptr if there is no item at this position. deviceTransform is the transform applied to the view.

27、QList<QGraphicsItem *> items(Qt::SortOrder order = Qt::DescendingOrder)

Returns an ordered list of all graphics items in the scene. The order is determined by the stacking order.

28、QList<QGraphicsItem *> items(const QPointF &pos, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform())

Returns the visible item (graphic item with effectiveOpacity() > 0) at the position of parameter 1 (see the 65th member function of QGraphicsItem for details).

Parameter 2 is the way to intersect with parameter 1, see the 42nd function below.

Parameter 3 is the sorting method in stacking order.

  • Qt::SortOrder: This enumeration describes the sorting method.
  • Qt::AscendingOrder: ascending order.
  • Qt::DescendingOrder: descending order.

29、QList<QGraphicsItem *> items(const QRectF &rect, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform())

28 overloaded functions.

30、QList<QGraphicsItem *> items(const QPolygonF &polygon, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform())

28 overloaded functions.

31、QList<QGraphicsItem *> items(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, Qt::SortOrder order = Qt::DescendingOrder, const QTransform &deviceTransform = QTransform())

28 overloaded functions.

32、QRectF itemsBoundingRect()

Computes and returns the bounding rectangle of all graphics items in the scene. This function works by iterating over all graph items, so for large scenes it can be slow.

33、QGraphicsItem *mouseGrabberItem()

Returns the current mouse grabber graphics item. The mouse grabber graphic item is the graphic item that receives all mouse events sent to the scene.

When a graphics item receives and accepts mouse down events, it becomes a mouse grabber, and it remains in the mouse grabber until one of the following events occurs:

The graphic item receives a mouse release event when no other mouse buttons are pressed.

Graphical items become invisible or disabled.

Graphic items are removed from the scene.

34、void removeItem(QGraphicsItem *item)

Removes the graphic item and all its children from the scene. Ownership of the graphic item will be passed to the caller (i.e. the scene will no longer delete the graphic item when it is destroyed).

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

Use Painter to render the source rect from the scene to the target.

  • If source is an empty rectangle, this function will use sceneRect() to determine what to render.
  • If target is an empty rectangle, the dimensions of the painter's painting device will be used.

Source rect content will be transformed to fit destination rect according to AspectRatioMode. By default, the aspect ratio is preserved and the source is scaled to fit the destination.

This feature is useful for capturing the contents of a scene to a drawing device (such as QImage) (e.g. to take a screenshot) or for printing using a QPrinter. For example:

QGraphicsScene scene;
scene.addItem(...
...
QPrinter printer(QPrinter::HighResolution);
printer.setPaperSize(QPrinter::A4);

QPainter painter(&printer);
scene.render(&painter);

36、QList<QGraphicsItem *> selectedItems()

Returns a list of all currently selected graphics items. Graphic items are returned in no particular order.

37、void setActivePanel(QGraphicsItem *item)

Activates a graphic item in the scene. If nullptr is passed in, the scene will disable any currently active panels. If the scene is currently inactive, the graphic item will remain inactive until the scene becomes active.

38、void setActiveWindow(QGraphicsWidget *widget)

Activate the widget in the scene. If nullptr is passed, the scene will disable any currently active windows.

39、void setFocus(Qt::FocusReason focusReason = Qt::OtherFocusReason)

Focus is set on the scene by sending a QFocusEvent to the scene with focusReason as the reason for the focus change.

40、void setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason = Qt::OtherFocusReason)

Sets the scene's focused graphics item to parameter 1 is the graphics item, after removing focus from any previous graphics item that might have had focus.

This function simply removes focus from any previous focusitem if parameter 1 is nullptr, or it does not accept focus (i.e. it does not have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible or not enabled.

If item is not nullptr, and the scene does not currently have focus (ie hasFocus() returns false), this function will automatically call setFocus().

41、void setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform)

Set selection area to path. All graphics items inside this area will be selected immediately, and all graphics items outside will be deselected. For a graphics item to be selected, it must be marked as selectable (QGraphicsItem::ItemIsSelectable).

42、void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, const QTransform &deviceTransform = QTransform())

overloaded functions. Parameter 2 is the selection mode.

  • Qt::ItemSelectionMode: This enumeration is used in the graphics view framework to specify how to select graphics items or how to determine whether shapes and graphics items collide.
  • Qt::ContainsItemShape: The output shape (QGraphicsItem::shape()) completely contains graphics items within the selection area, and graphics items that intersect the outline of the area are not included.
  • Qt::IntersectsItemShape: The output shape (QGraphicsItem::shape()) is the graphics item that is completely contained within the selection area and the graphics item that intersects the outline of the area. This is a common pattern for box selection.
  • Qt::ContainsItemBoundingRect: The output bounding rectangle (QGraphicsItem::boundingRect()) is completely contained within the graphics item in the selection area. Graphical items that intersect the outline of the area are not included.
  • Qt::IntersectsItemBoundingRect: The output bounding rectangle (QGraphicsItem::boundingRect()) contains graphics items that are completely contained within the selection area and graphics items that intersect the outline of the area. This method is typically used to identify areas that need to be redrawn.

43、void setSelectionArea(const QPainterPath &path, Qt::ItemSelectionOperation selectionOperation, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape, const QTransform &deviceTransform = QTransform())

Overloaded function, parameter 2 determines how to handle the currently selected graphic item.

  • Qt::ItemSelectionOperation: This enumeration is used in the scene to specify how to handle the currently selected graphics item when setting the selection area.
  • Qt::ReplaceSelection: The currently selected graphics item is deselected, and the graphics item in the specified area is selected.
  • Qt::AddToSelection: The state of the currently selected graphics item remains unchanged, and the graphics item in the specified area is selected.

44、void setStyle(QStyle *style)

Set the style for the QGraphicsWidget in the scene.

45、QList<QGraphicsView *> views()

Get a list of views showing the current scene.

Five, event member function

1、void contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)

Context menu events. The default implementation forwards events to the topmost visible graphics item. If no graphics item accepts a context menu event at this position, the event will be ignored.

2、void dragEnterEvent(QGraphicsSceneDragDropEvent *event)

Drag and drop into the event. The default implementation accepts events.

3、void dragLeaveEvent(QGraphicsSceneDragDropEvent *event)

Drag and drop event.

4、void dragMoveEvent(QGraphicsSceneDragDropEvent *event)

Drag move event.

5、void dropEvent(QGraphicsSceneDragDropEvent *event)

Drag and drop events.

6、bool event(QEvent *event)

Implemented from QObject::event(). Handles event events and dispatches them to the appropriate event handlers. In addition to calling the convenience event handler, this function is also responsible for converting mousemove events to mouseover events when there is no mouse gripper item. Mouseover events are passed directly to graphical items. The scene does not have convenient processing functions for mouse enter, mouse hover, and mouse leave events. These events are handled in event().

7、bool eventFilter(QObject *watched, QEvent *event)

Implemented from QObject::eventFilter(). The scene filters QApplication's events to detect palette and font changes.

8、void focusInEvent(QFocusEvent *focusEvent)

Receive focus events. The default implementation sets focus on the scene, then on the last focused item (the last graphics item to have focus before it lost focus).

9、void helpEvent(QGraphicsSceneHelpEvent *helpEvent)

help event. The event is of type QEvent::ToolTip, which is created when a tooltip is requested. The default implementation displays a tooltip for the topmost visible item (the item with the highest z-value) at the mouse cursor position. If no item has a tooltip set, this function does nothing.

10、void inputMethodEvent(QInputMethodEvent *event)

Input method events. The default implementation forwards the event to focusItem(). This function does nothing if no graphics item currently has focus or if the currently focused item does not accept an input method.

11、void keyPressEvent(QKeyEvent *keyEvent)

Keyboard press event. The default implementation forwards events to the currently focused graphics item.

12、void keyReleaseEvent(QKeyEvent *keyEvent)

Key release event. The default implementation forwards events to the currently focused graphics item.

13、void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)

Mouse double click event. Event process: Double-click the scene --> the scene will first receive the mouse press event --> then receive the release event (that is, click) --> then the double-click event --> finally the release event.

14. void mouseMoveEvent (t *mouseEvent after QGraphicsSceneMouseEven is pressed)

Mouse move event (can be triggered by moving without pressing). The default implementation depends on the mouse grabber state. If a mouse grabber graphic item exists, the event will be sent to the mouse grabber. If there is any graphics item at the current position that accepts a hover event, the event is converted to a hover event and accepted.

15、void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)

Mouse down event. The default implementation depends on the state of the scene. If a mouse grabber graphic item exists, the event will be sent to the mouse grabber. Otherwise, it is forwarded to the topmost visible graphic item that accepted the mouse event from the scene position where the event started, and that graphic item becomes the mousegrabber graphic item. If there are no graphics items at the given position in the scene, the selection area is reset, any focused graphics item loses its input focus, and the event is ignored.

16、void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)

Mouse release event. The default implementation depends on the mouse grabber state. If there is no mouse grabber, the event will be ignored. If there is a mouse grabber graphic item, the event will be sent to the mouse grabber graphic item.

17、bool sendEvent(QGraphicsItem *item, QEvent *event)

Sends an event to the graph item, returns false if the event is filtered or the graph item is disabled. Otherwise, returns the value returned by the event handler. Usage is similar to QApplication::postEvent() to send events:

qApp->postEvent(this, event);

18、void wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)

Mouse wheel event. By default, events are delivered to the topmost visible graphics item under the cursor. If omitted, the event will propagate down until the event is accepted or reaches the scene. The event is ignored if no graphics item accepts the event.

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↓↓

Guess you like

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