1. Computing

Using Margins and Padding Properties in Delphi's VCL

Align UI better using Margins and Padding

From , former About.com Guide

Allign UI better using Margins and Padding

Allign UI better using Margins and Padding

Article applies to Delphi >= 2006

One of the neateast new properties (in Delphi versions 2006 and up) you can find in the Object Inspector are the Margins, Padding and AllignWithMargins.

Introduced in Delphi 2006, the Margins and Padding properties allow for much easier/cleaner positioning of visual controls inside their containers.

Well, the above is true if you, like me, tend to align controls in their containers using the Align property (with a few TSplitter's* where needed).

For me, there's no user interface like the one you can set up using just a few panels, their Align property and now with the help of Margins and Padding the UI gets even better.

Margins and AlignWithMargins

The Margins property, of type TMargins, along with the associated AlignWithMargins affects the positioning of the control inside its parent control.

Margins exposes 4 values: Top, Right, Bottom, Left. Each value represent the number of pixels used for the margin for each of the sides of the control.

For example, drop a panel a form. Panel's Align property is set to alTop and AlignWithMargins is true, with the Margin.Top value set to 5 - the distance between the top border of the form and the top border of the panel will be 5 pixels.

Note that the default value for Margins is 3 (Top, Right, Bottom, Left)

If you now drop another panel below the first one. With Panel2.Align = alTop, set its Margin.Top to 10, make sure AllignWithMargins is true ... the distance between panel 1 and panel 2 is now 13 pixels - 3 from Panel1.Margin.Bottom and 10 from Panel2.Margin.Top.

In short: when the margin (all 4 values) for a control is set to 10 pixels, the control, when alligned, will not come closer than 10 pixels to the edge of its container.

Padding

Pading property, of type TPadding = class(TMargins), affects the positioning of control's child controls.

Child controls that are aligned inside a parent are positioned inside the parent according to parent's padding values (+ their own Margins).

Padding is much like Margins - but while Margins afects the control itself, Padding affects child controls that are aligned using their Align property inside their parent.

TSplitter and Panels with AlignWithMargins ... no go :(

Warning on using Margins and the TSplitter: splitter will not work when two controls with AlignWithMargins set to true are put one next to other. The problem is in Splitter's FindControl private method .. but more on that some other time...

©2013 About.com. All rights reserved.