QGraphicsAnchorLayout Class

The QGraphicsAnchorLayout class provides a layout where one can anchor widgets together in Graphics View. More...

Header: #include <QGraphicsAnchorLayout>
qmake: QT += widgets
Since: Qt 4.6
Inherits: QGraphicsLayout

This class was introduced in Qt 4.6.

Detailed Description

The anchor layout allows developers to specify how widgets should be placed relative to each other, and to the layout itself. The specification is made by adding anchors to the layout by calling addAnchor(), addAnchors() or addCornerAnchors().

Existing anchors in the layout can be accessed with the anchor() function. Items that are anchored are automatically added to the layout, and if items are removed, all their anchors will be automatically removed.

Using an anchor layout to align simple colored widgets.

Anchors are always set up between edges of an item, where the "center" is also considered to be an edge. Consider the following example:

 layout->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight);
 layout->addAnchor(b, Qt::AnchorTop, a, Qt::AnchorBottom);

Here, the right edge of item a is anchored to the left edge of item b and the bottom edge of item a is anchored to the top edge of item b, with the result that item b will be placed diagonally to the right and below item b.

The addCornerAnchors() function provides a simpler way of anchoring the corners of two widgets than the two individual calls to addAnchor() shown in the code above. Here, we see how a widget can be anchored to the top-left corner of the enclosing layout:

 layout->addCornerAnchors(a, Qt::TopLeftCorner, layout, Qt::TopLeftCorner);

In cases where anchors are used to match the widths or heights of widgets, it is convenient to use the addAnchors() function. As with the other functions for specifying anchors, it can also be used to anchor a widget to a layout.

Size Hints and Size Policies in an Anchor Layout

QGraphicsAnchorLayout respects each item's size hints and size policies. Note that there are some properties of QSizePolicy that are not respected.

Spacing within an Anchor Layout

The layout may distribute some space between the items. If the spacing has not been explicitly specified, the actual amount of space will usually be 0.

However, if the first edge is the opposite of the second edge (e.g., the right edge of the first widget is anchored to the left edge of the second widget), the size of the anchor will be queried from the style through a pixel metric: PM_LayoutHorizontalSpacing for horizontal anchors and PM_LayoutVerticalSpacing for vertical anchors.

If the spacing is negative, the items will overlap to some extent.

Known Issues

There are some features that QGraphicsAnchorLayout currently does not support. This might change in the future, so avoid using these features if you want to avoid any future regressions in behaviour:

See also QGraphicsLinearLayout, QGraphicsGridLayout, and QGraphicsLayout.