Anchor Sides

From Lazarus wiki
Revision as of 13:12, 9 February 2005 by Vincent (talk | contribs) (improved layout)
Jump to navigationJump to search

Anchor Sides

There are some new properties and methods for automatic layout of controls. You can now setup controls to keep a certain distance to other controls, or center relative to other controls. See below for examples.

Each of the four sides of a control (Left, Top, Right, Bottom) can now be anchored/bound to a side of another control. For example you can now anchor the left side of TEdit to the right side of a TLabel. Everytime the Label is moved or resized the Edit's left side will follow, which normally results in moving the Edit parallel to the Label.

Example 1

+--------+ +-------+
| Label1 | | Edit1 |
+--------+ |       |
           +-------+

In code

Edit1.AnchorSide[akLeft].Side:=asrRight;
Edit1.AnchorSide[akLeft].Control:=Label1;
Edit1.Anchors:=Edit1.Anchors+[akLeft];

You can define the distance with the BorderSpacing properties:

Edit1.BorderSpacing.Left:=10;

The same can be done with the method:

Edit1.AnchorToNeighbour(akLeft,10,Label1);

Notes

The Edit1.Left will follow Label1.Left+Label1.Width, not the other way around. That means, moving Label1 will move Edit1. But moving Edit1 will be undone by the LCL. If you also anchor the right side of Label1 to the left side of Edit1, you created a circle, and this can result together with some other autosize properties in an infinite loop. Detection of circles is not yet implemented.

Example 2

You can anchor the Edit's top side to follow the Label's top side:

+--------+ +-------+
| Label1 | | Edit1 |
+--------+ |       |
           +-------+
Edit1.AnchorSide[akTop].Side:=asrTop;
Edit1.AnchorSide[akTop].Control:=Label1;
Edit1.Anchors:=Edit1.Anchors+[akTop];

The same can be done with the method:

Edit1.AnchorParallel(akTop,0,Label1);

Example 3

Centering a Label vertically to an Edit:

          +-------+

+--------+ | | | Label1 | | Edit1 | +--------+ | |

          +-------+
Edit1.AnchorSide[akTop].Side:=asrCenter;
Edit1.AnchorSide[akTop].Control:=Label1;
Edit1.Anchors:=Edit1.Anchors+[akTop]-[akBottom];

The same can be done with the method:

Edit1.AnchorVerticalCenterTo(Label1);

Obviously anchoring the bottom side of Edit1 does not make sense when centering.


New property

property AnchorSide[Kind: TAnchorKind]: TAnchorSide read GetAnchorSide;

This is not published in the object inspector. You can edit it in the designer via the anchor editor (Menu: View -> View anchor editor, or click on button of 'Anchors' property).

New methods to easy configure common layouts

procedure AnchorToNeighbour(Side: TAnchorKind; Space: integer;
                            Sibling: TControl);
procedure AnchorParallel(Side: TAnchorKind; Space: integer;
                         Sibling: TControl);
procedure AnchorHorizontalCenterTo(Sibling: TControl);
procedure AnchorVerticalCenterTo(Sibling: TControl);