QGraphicsScene Class

The QGraphicsScene class provides a surface for managing a large number of 2D graphical items. More...

Header: #include <QGraphicsScene>
qmake: QT += widgets
Since: Qt 4.2
Inherits: QObject

This class was introduced in Qt 4.2.

Public Types

enum ItemIndexMethod { BspTreeIndex, NoIndex }
enum SceneLayer { ItemLayer, BackgroundLayer, ForegroundLayer, AllLayers }

Properties

Public Functions

QBrush backgroundBrush() const
int bspTreeDepth() const
bool focusOnTouch() const
QFont font() const
QBrush foregroundBrush() const
QGraphicsScene::ItemIndexMethod itemIndexMethod() const
qreal minimumRenderSize() const
QPalette palette() const
QRectF sceneRect() const
void setBackgroundBrush(const QBrush &brush)
void setBspTreeDepth(int depth)
void setFocusOnTouch(bool enabled)
void setFont(const QFont &font)
void setForegroundBrush(const QBrush &brush)
void setItemIndexMethod(QGraphicsScene::ItemIndexMethod method)
void setMinimumRenderSize(qreal minSize)
void setPalette(const QPalette &palette)
void setSceneRect(const QRectF &rect)
void setSceneRect(qreal x, qreal y, qreal w, qreal h)
void setStickyFocus(bool enabled)
bool stickyFocus() const

Detailed Description

The class serves as a container for QGraphicsItems. It is used together with QGraphicsView for visualizing graphical items, such as lines, rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is part of the Graphics View Framework.

QGraphicsScene also provides functionality that lets you efficiently determine both the location of items, and for determining what items are visible within an arbitrary area on the scene. With the QGraphicsView widget, you can either visualize the whole scene, or zoom in and view only parts of the scene.

Example:

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

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

Note that QGraphicsScene has no visual appearance of its own; it only manages the items. You need to create a QGraphicsView widget to visualize the scene.

To add items to a scene, you start off by constructing a QGraphicsScene object. Then, you have two options: either add your existing QGraphicsItem objects by calling addItem(), or you can call one of the convenience functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(), addRect(), or addText(), which all return a pointer to the newly added item. The dimensions of the items added with these functions are relative to the item's coordinate system, and the items position is initialized to (0, 0) in the scene.

You can then visualize the scene using QGraphicsView. When the scene changes, (e.g., when an item moves or is transformed) QGraphicsScene emits the changed() signal. To remove an item, call removeItem().

QGraphicsScene uses an indexing algorithm to manage the location of items efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an algorithm suitable for large scenes where most items remain static (i.e., do not move around). You can choose to disable this index by calling setItemIndexMethod(). For more information about the available indexing algorithms, see the itemIndexMethod property.

The scene's bounding rect is set by calling setSceneRect(). Items can be placed at any position on the scene, and the size of the scene is by default unlimited. The scene rect is used only for internal bookkeeping, maintaining the scene's item index. If the scene rect is unset, QGraphicsScene will use the bounding area of all items, as returned by itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a relatively time consuming function, as it operates by collecting positional information for every item on the scene. Because of this, you should always set the scene rect when operating on large scenes.

One of QGraphicsScene's greatest strengths is its ability to efficiently determine the location of items. Even with millions of items on the scene, the items() functions can determine the location of an item within a few milliseconds. There are several overloads to items(): one that finds items at a certain position, one that finds items inside or intersecting with a polygon or a rectangle, and more. The list of returned items is sorted by stacking order, with the topmost item being the first item in the list. For convenience, there is also an itemAt() function that returns the topmost item at a given position.

QGraphicsScene maintains selection information for the scene. To select items, call setSelectionArea(), and to clear the current selection, call clearSelection(). Call selectedItems() to get the list of all selected items.

Event Handling and Propagation

Another responsibility that QGraphicsScene has, is to propagate events from QGraphicsView. To send an event to a scene, you construct an event that inherits QEvent, and then send it using, for example, QCoreApplication::sendEvent(). event() is responsible for dispatching the event to the individual items. Some common events are handled by convenience event handlers. For example, key press events are handled by keyPressEvent(), and mouse press events are handled by mousePressEvent().

Key events are delivered to the focus item. To set the focus item, you can either call setFocusItem(), passing an item that accepts focus, or the item itself can call QGraphicsItem::setFocus(). Call focusItem() to get the current focus item. For compatibility with widgets, the scene also maintains its own focus information. By default, the scene does not have focus, and all key events are discarded. If setFocus() is called, or if an item on the scene gains focus, the scene automatically gains focus. If the scene has focus, hasFocus() will return true, and key events will be forwarded to the focus item, if any. If the scene loses focus, (i.e., someone calls clearFocus()) while an item has focus, the scene will maintain its item focus information, and once the scene regains focus, it will make sure the last focus item regains focus.

For mouse-over effects, QGraphicsScene dispatches hover events. If an item accepts hover events (see QGraphicsItem::acceptHoverEvents()), it will receive a GraphicsSceneHoverEnter event when the mouse enters its area. As the mouse continues moving inside the item's area, QGraphicsScene will send it GraphicsSceneHoverMove events. When the mouse leaves the item's area, the item will receive a GraphicsSceneHoverLeave event.

All mouse events are delivered to the current mouse grabber item. An item becomes the scene's mouse grabber if it accepts mouse events (see QGraphicsItem::acceptedMouseButtons()) and it receives a mouse press. It stays the mouse grabber until it receives a mouse release when no other mouse buttons are pressed. You can call mouseGrabberItem() to determine what item is currently grabbing the mouse.

See also QGraphicsItem and QGraphicsView.

Member Type Documentation

enum QGraphicsScene::ItemIndexMethod

This enum describes the indexing algorithms QGraphicsScene provides for managing positional information about items on the scene.

ConstantValueDescription
QGraphicsScene::BspTreeIndex0A Binary Space Partitioning tree is applied. All QGraphicsScene's item location algorithms are of an order close to logarithmic complexity, by making use of binary search. Adding, moving and removing items is logarithmic. This approach is best for static scenes (i.e., scenes where most items do not move).
QGraphicsScene::NoIndex-1No index is applied. Item location is of linear complexity, as all items on the scene are searched. Adding, moving and removing items, however, is done in constant time. This approach is ideal for dynamic scenes, where many items are added, moved or removed continuously.

See also setItemIndexMethod() and bspTreeDepth.

enum QGraphicsScene::SceneLayer

This enum describes the rendering layers in a QGraphicsScene. When QGraphicsScene draws the scene contents, it renders each of these layers separately, in order.

Each layer represents a flag that can be OR'ed together when calling functions such as invalidate() or QGraphicsView::invalidateScene().

ConstantValueDescription
QGraphicsScene::ItemLayer0x1The item layer. QGraphicsScene renders all items are in this layer by calling the virtual function drawItems(). The item layer is drawn after the background layer, but before the foreground layer.
QGraphicsScene::BackgroundLayer0x2The background layer. QGraphicsScene renders the scene's background in this layer by calling the virtual function drawBackground(). The background layer is drawn first of all layers.
QGraphicsScene::ForegroundLayer0x4The foreground layer. QGraphicsScene renders the scene's foreground in this layer by calling the virtual function drawForeground(). The foreground layer is drawn last of all layers.
QGraphicsScene::AllLayers0xffffAll layers; this value represents a combination of all three layers.

This enum was introduced or modified in Qt 4.3.

See also invalidate() and QGraphicsView::invalidateScene().

Property Documentation

backgroundBrush : QBrush

This property holds the background brush of the scene.

Set this property to changes the scene's background to a different color, gradient or texture. The default background brush is Qt::NoBrush. The background is drawn before (behind) the items.

Example:

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

 // a blue background
 scene.setBackgroundBrush(Qt::blue);

 // a gradient background
 QRadialGradient gradient(0, 0, 10);
 gradient.setSpread(QGradient::RepeatSpread);
 scene.setBackgroundBrush(gradient);

QGraphicsScene::render() calls drawBackground() to draw the scene background. For more detailed control over how the background is drawn, you can reimplement drawBackground() in a subclass of QGraphicsScene.

Access functions:

QBrush backgroundBrush() const
void setBackgroundBrush(const QBrush &brush)

bspTreeDepth : int

This property holds the depth of QGraphicsScene's BSP index tree

This property has no effect when NoIndex is used.

This value determines the depth of QGraphicsScene's BSP tree. The depth directly affects QGraphicsScene's performance and memory usage; the latter growing exponentially with the depth of the tree. With an optimal tree depth, QGraphicsScene can instantly determine the locality of items, even for scenes with thousands or millions of items. This also greatly improves rendering performance.

By default, the value is 0, in which case Qt will guess a reasonable default depth based on the size, location and number of items in the scene. If these parameters change frequently, however, you may experience slowdowns as QGraphicsScene retunes the depth internally. You can avoid potential slowdowns by fixating the tree depth through setting this property.

The depth of the tree and the size of the scene rectangle decide the granularity of the scene's partitioning. The size of each scene segment is determined by the following algorithm:

 QSizeF segmentSize = sceneRect().size() / pow(2, depth - 1);

The BSP tree has an optimal size when each segment contains between 0 and 10 items.

This property was introduced in Qt 4.3.

Access functions:

int bspTreeDepth() const
void setBspTreeDepth(int depth)

See also itemIndexMethod.

focusOnTouch : bool

This property holds whether items gain focus when receiving a touch begin event.

The usual behavior is to transfer focus only when an item is clicked. Often a tap on a touchpad is interpreted as equivalent to a mouse click by the operating system, generating a synthesized click event in response. However, at least on macOS you can configure this behavior.

By default, QGraphicsScene also transfers focus when you touch on a trackpad or similar. If the operating system is configured to not generate a synthetic mouse click on tapping the trackpad, this is surprising. If the operating system does generate synthetic mouse clicks on tapping the trackpad, the focus transfer on starting a touch gesture is unnecessary.

With focusOnTouch switched off, QGraphicsScene behaves as one would expect on macOS.

The default value is true, ensuring that the default behavior is just as in Qt versions prior to 5.12. Set to false to prevent touch events from triggering focus changes.

This property was introduced in Qt 5.12.

Access functions:

bool focusOnTouch() const
void setFocusOnTouch(bool enabled)

font : QFont

This property holds the scene's default font

This property provides the scene's font. The scene font defaults to, and resolves all its entries from, QApplication::font.

If the scene's font changes, either directly through setFont() or indirectly when the application font changes, QGraphicsScene first sends itself a FontChange event, and it then sends FontChange events to all top-level widget items in the scene. These items respond by resolving their own fonts to the scene, and they then notify their children, who again notify their children, and so on, until all widget items have updated their fonts.

Changing the scene font, (directly or indirectly through QApplication::setFont(),) automatically schedules a redraw the entire scene.

This property was introduced in Qt 4.4.

Access functions:

QFont font() const
void setFont(const QFont &font)

See also QWidget::font, QApplication::setFont(), palette, and style().

foregroundBrush : QBrush

This property holds the foreground brush of the scene.

Change this property to set the scene's foreground to a different color, gradient or texture.

The foreground is drawn after (on top of) the items. The default foreground brush is Qt::NoBrush ( i.e. the foreground is not drawn).

Example:

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

 // a white semi-transparent foreground
 scene.setForegroundBrush(QColor(255, 255, 255, 127));

 // a grid foreground
 scene.setForegroundBrush(QBrush(Qt::lightGray, Qt::CrossPattern));

QGraphicsScene::render() calls drawForeground() to draw the scene foreground. For more detailed control over how the foreground is drawn, you can reimplement the drawForeground() function in a QGraphicsScene subclass.

Access functions:

QBrush foregroundBrush() const
void setForegroundBrush(const QBrush &brush)

itemIndexMethod : ItemIndexMethod

This property holds the item indexing method.

QGraphicsScene applies an indexing algorithm to the scene, to speed up item discovery functions like items() and itemAt(). Indexing is most efficient for static scenes (i.e., where items don't move around). For dynamic scenes, or scenes with many animated items, the index bookkeeping can outweigh the fast lookup speeds.

For the common case, the default index method BspTreeIndex works fine. If your scene uses many animations and you are experiencing slowness, you can disable indexing by calling setItemIndexMethod(NoIndex).

Access functions:

QGraphicsScene::ItemIndexMethod itemIndexMethod() const
void setItemIndexMethod(QGraphicsScene::ItemIndexMethod method)

See also bspTreeDepth.

minimumRenderSize : qreal

This property holds the minimal view-transformed size an item must have to be drawn

When the scene is rendered, any item whose width or height, transformed to the target view, is smaller that minimumRenderSize(), will not be rendered. If an item is not rendered and it clips its children items they will also not be rendered. Set this value to speed up rendering of scenes with many objects rendered on a zoomed out view.

The default value is 0. If unset, or if set to 0 or a negative value, all items will always be rendered.

For example, setting this property can be especially useful if a scene is rendered by multiple views, one of which serves as an overview which always displays all items. In scenes with many items, such a view will use a high scaling factor so that all items can be shown. Due to the scaling, smaller items will only make an insignificant contribution to the final rendered scene. To avoid drawing these items and reduce the time necessary to render the scene, you can call setMinimumRenderSize() with a non-negative value.

Note: Items that are not drawn as a result of being too small, are still returned by methods such as items() and itemAt(), and participate in collision detection and interactions. It is recommended that you set minimumRenderSize() to a value less than or equal to 1 in order to avoid large unrendered items that are interactive.

This property was introduced in Qt 5.4.

Access functions:

qreal minimumRenderSize() const
void setMinimumRenderSize(qreal minSize)

See also QStyleOptionGraphicsItem::levelOfDetailFromTransform().

palette : QPalette

This property holds the scene's default palette

This property provides the scene's palette. The scene palette defaults to, and resolves all its entries from, QApplication::palette.

If the scene's palette changes, either directly through setPalette() or indirectly when the application palette changes, QGraphicsScene first sends itself a PaletteChange event, and it then sends PaletteChange events to all top-level widget items in the scene. These items respond by resolving their own palettes to the scene, and they then notify their children, who again notify their children, and so on, until all widget items have updated their palettes.

Changing the scene palette, (directly or indirectly through QApplication::setPalette(),) automatically schedules a redraw the entire scene.

This property was introduced in Qt 4.4.

Access functions:

QPalette palette() const
void setPalette(const QPalette &palette)

See also QWidget::palette, QApplication::setPalette(), font, and style().

sceneRect : QRectF

This property holds the scene rectangle; the bounding rectangle of the scene

The scene rectangle defines the extent of the scene. It is primarily used by QGraphicsView to determine the view's default scrollable area, and by QGraphicsScene to manage item indexing.

If unset, or if set to a null QRectF, sceneRect() will return the largest bounding rect of all items on the scene since the scene was created (i.e., a rectangle that grows when items are added to or moved in the scene, but never shrinks).

Access functions:

QRectF sceneRect() const
void setSceneRect(const QRectF &rect)
void setSceneRect(qreal x, qreal y, qreal w, qreal h)

See also width(), height(), and QGraphicsView::sceneRect.

stickyFocus : bool

This property holds whether clicking into the scene background will clear focus

In a QGraphicsScene with stickyFocus set to true, focus will remain unchanged when the user clicks into the scene background or on an item that does not accept focus. Otherwise, focus will be cleared.

By default, this property is false.

Focus changes in response to a mouse press. You can reimplement mousePressEvent() in a subclass of QGraphicsScene to toggle this property based on where the user has clicked.

This property was introduced in Qt 4.6.

Access functions:

bool stickyFocus() const
void setStickyFocus(bool enabled)

See also clearFocus() and setFocusItem().