Difference between revisions of "LCL AutoSizing"

From Free Pascal wiki
Jump to navigationJump to search
(Remove link to empty (about to be deleted) page)
 
(7 intermediate revisions by 2 users not shown)
Line 1: Line 1:
==Обзор / Терминология==
+
{{LCL AutoSizing}}
  
На этой странице объясняется алгоритм автомасштабирования в LCL. AutoSizing означает здесь: автоматическое изменение размера и перемещение элементов управления LCL.
+
==Overview / Terminology==
  
Если вам просто интересно, как использовать свойства AutoSize, см. [[Autosize_/_Layout/ru#Разметка (Layout)|Autosize/Layout]].
+
This page explains the LCL auto sizing algorithm. AutoSizing means here: Automatic resizing and repositioning of LCL controls.
  
==Свойства==
+
If you are merely interested in how to use the AutoSize properties, see [[Autosize / Layout]].
  
Следующие свойства определяют поведение автомасштабирования в LCL:
+
==Properties==
 +
 
 +
The following properties defines the behavior of the LCL autosizing:
  
 
*Current Left,Top,Width,Height,ClientWidth,ClientHeight
 
*Current Left,Top,Width,Height,ClientWidth,ClientHeight
Line 19: Line 21:
 
*Constraints
 
*Constraints
  
Для совместимости с Delphi LCL поддерживает метод AdjustClientRect, который является расширением свойств ChildSize.LeftRightSpacing/TopBottomSpacing.
+
For Delphi compatibility the LCL supports the method AdjustClientRect which is an extension to the ChildSizing.LeftRightSpacing/TopBottomSpacing properties.
  
==Порядок==
+
==Order==
  
===Обзор===
+
===Overview===
  
Автомасштабирование работает в несколько этапов:
+
The autosizing works in several phases:
  
*DisableAutosizing. На первом этапе приложение изменяет свойства, создает или удаляет элементы управления. Вся форма заблокирована. Отсутствует автоматическая настройка, никакие границы в виджет не отправляются .
+
*DisableAutosizing. In the first phase the application changes properties, creates or deletes controls. The whole form is locked. No Autosizing is done, no bounds are sent to the widgetset.
*EnableAutoSizing. Вызывается [методом] DoAllAutoSize родительской формы.
+
*EnableAutoSizing. The parent form DoAllAutoSize is called.
*Все необходимые дескрипторы создаются рекурсивно [методом] TWinControl.DoAllAutoSize. Они еще не сделаны видимыми.
+
*All needed handles are created recursively by TWinControl.DoAllAutoSize. They are not yet made visible.
*[Метод] TControl.DoAllAutoSize вычисляет границы, вызывая DoAutoSize для всех элементов управления. Он делает это в цикле, пока никакие границы не изменены.
+
*TControl.DoAllAutoSize computes the bounds by calling DoAutoSize for all controls. It does that in a loop until no bound changes.
*Границы отправляются в виджет (TWinControl.RealizeBoundsRecursive вызывает RealizeBounds).
+
*The bounds are sent to the widgetset (TWinControl.RealizeBoundsRecursive calling RealizeBounds).
*Дескрипторы становятся видимыми (если [свойство] HandleObjectShouldBeVisible [имеет значение True] и not Showing, то [вызывается] UpdateShowing).
+
*The handles are made visible (if HandleObjectShouldBeVisible and not Showing then).
  
В основном свойство AutoSizing работает в следующем порядке:
+
Basically the AutoSizing properties work in this order:
  
*Ограничения применяются к каждому шагу.
+
*The constraints are applied to every step.
*Сначала идет выравнивание в порядке alTop, alBottom, alLeft, alRight и, наконец, alClient. Например, alLeft имеет 3 выровненных стороны и одну свободную сторону. Свободная сторона обрабатывается приведенными ниже правилами. BorderSpacing применяется к выровненным сторонам. alCustom и alNone не имеют выровненных сторон.
+
*First comes the Align in order alTop, alBottom, alLeft, alRight and finally alClient. For example alLeft has 3 aligned sides and one free side. The free side is handled by the below rules. BorderSpacing is applied to aligned sides. alCustom and alNone have no aligned sides.
*Далее идет ChildSizing. Если ChildSizing.Layout не [в значении] cclNone, все дочерние элементы управления со [значениями] Align=alNone, Anchors=[akLeft,akTop] и элементы управления без AnchorSide масштабируются/репозиционируются. Эти дочерние элементы управления называются на этой странице "элементы управления без выравнивания".
+
*Next comes ChildSizing. If ChildSizing.Layout is not cclNone then all child controls with Align=alNone, Anchors=[akLeft,akTop] and no AnchorSide controls are resized/repositioned. These child controls are called on this page "non aligned controls".
*Затем идет AutoSize. Если ChildSizing.Layout [имеет значение] cclNone, тогда все "элементы управления без выравнивания" перемещаются кверху и влево, а элемент управления сужается или расширяется, чтобы соответствовать всем его дочерним элементам (а не только "элементам управления без выравнивания").
+
*Next comes AutoSize. If ChildSizing.Layout is cclNone then all "non aligned controls" are moved to the top, left and the control is shrunken or enlarged to fit around all its children (not only the "non aligned controls").  
*Потом идут якоря (привязки). Только те стороны [считаются] привязанными, которые не обрабатываются [свойством] Align (например, akRight в alLeft). Если у элемента управления установлено [свойство] AnchorSide, сторона [этого контрола] будет выровнена к стороне другого элемента управления. В противном случае применяются правила привязки по умолчанию, которые в основном аналогичны Delphi.
+
*Next comes the Anchors. Only those sides are anchored, which were not handled by Align (e.g. akRight on alLeft). If an AnchorSide control is set the side will be aligned to the side of the other control. Otherwise the default anchor rules apply, which are mostly similar to the Delphi ones.
*Каждое изменение границ запускает событие OnResize/OnChangeBounds, которое может использоваться приложением для выполнения произвольных действий.
+
*every change of bounds triggers an OnResize/OnChangeBounds event, which may be used by the application to do arbitrary things.
  
 
===Algorithm for Align and Anchors===
 
===Algorithm for Align and Anchors===
Line 90: Line 92:
  
 
see [[Autosize / Layout]].
 
see [[Autosize / Layout]].
 
[[Category:LCL]]
 
[[Category:GUI]]
 
[[Category:Layout]]
 

Latest revision as of 15:35, 3 January 2020

English (en) русский (ru)

Overview / Terminology

This page explains the LCL auto sizing algorithm. AutoSizing means here: Automatic resizing and repositioning of LCL controls.

If you are merely interested in how to use the AutoSize properties, see Autosize / Layout.

Properties

The following properties defines the behavior of the LCL autosizing:

  • Current Left,Top,Width,Height,ClientWidth,ClientHeight
  • Loaded Left,Top,Width,Height,ClientWidth,ClientHeight
  • AutoSize
  • Anchors
  • AnchorSides
  • Align
  • BorderSpacing
  • ChildSizing
  • Constraints

For Delphi compatibility the LCL supports the method AdjustClientRect which is an extension to the ChildSizing.LeftRightSpacing/TopBottomSpacing properties.

Order

Overview

The autosizing works in several phases:

  • DisableAutosizing. In the first phase the application changes properties, creates or deletes controls. The whole form is locked. No Autosizing is done, no bounds are sent to the widgetset.
  • EnableAutoSizing. The parent form DoAllAutoSize is called.
  • All needed handles are created recursively by TWinControl.DoAllAutoSize. They are not yet made visible.
  • TControl.DoAllAutoSize computes the bounds by calling DoAutoSize for all controls. It does that in a loop until no bound changes.
  • The bounds are sent to the widgetset (TWinControl.RealizeBoundsRecursive calling RealizeBounds).
  • The handles are made visible (if HandleObjectShouldBeVisible and not Showing then).

Basically the AutoSizing properties work in this order:

  • The constraints are applied to every step.
  • First comes the Align in order alTop, alBottom, alLeft, alRight and finally alClient. For example alLeft has 3 aligned sides and one free side. The free side is handled by the below rules. BorderSpacing is applied to aligned sides. alCustom and alNone have no aligned sides.
  • Next comes ChildSizing. If ChildSizing.Layout is not cclNone then all child controls with Align=alNone, Anchors=[akLeft,akTop] and no AnchorSide controls are resized/repositioned. These child controls are called on this page "non aligned controls".
  • Next comes AutoSize. If ChildSizing.Layout is cclNone then all "non aligned controls" are moved to the top, left and the control is shrunken or enlarged to fit around all its children (not only the "non aligned controls").
  • Next comes the Anchors. Only those sides are anchored, which were not handled by Align (e.g. akRight on alLeft). If an AnchorSide control is set the side will be aligned to the side of the other control. Otherwise the default anchor rules apply, which are mostly similar to the Delphi ones.
  • every change of bounds triggers an OnResize/OnChangeBounds event, which may be used by the application to do arbitrary things.

Algorithm for Align and Anchors

The main method is TWinControl.AlignControls.

  1. init RemainingClientRect to ClientRect and RemainingBorderSpace to Rect(0,0,0,0)
  2. call AdjustClient to adjust RemainingClientRect
  3. apply ChildSizing.LeftRightSpacing,ChildSizing.TopBottomSpacing
  4. call DoAlign with alTop,alBottom,alLeft,alRight,alClient,alCustom,alNone
    1. DoAlign collects child controls with this Align value and call for each such control DoPosition
      1. DoPosition calculates the new Left,Top,Width,Height


DoAutoSize

This is called by DoAllAutoSize and should not be called by the application. Applications should call AdjustSize and/or InvalidatePreferredSize.

If it is not overriden the normal TWinControl.DoAutoSize does the following, when AutoSize=true:

It will move "non aligned controls" - child controls with default anchors (Anchors=[akLeft,akTop],Align=alNone). It moves all of them the same amount, so their total bounding box fits left and top. The spacing of BorderSpacing and ChildSizing is considered.

Before the move, there is space to the left and above the buttons: Autosize before move childs.png

After the move: Autosize after move childs.png

Then the preferred size of the control is computed. This calculation considers child controls, Align, Anchors, Constraints, ChildSizing.Layout and the other LCL properties.

The control is resized: Autosize after shrink.png


See also: Align and parent AutoSize

DisableAutoSizing/EnableAutosizing

see here.

Differences from Delphi

  • Delphi has no BorderSpacing, AnchorSides, ChildSizing.
  • Delphi does not support AutoSize and Align on all controls.
  • Delphi's AutoSize algorithm does not support nested autosized controls with the Align property. For example a Panel1 with Align=alTop in a Panel2 and both panels have AutoSize=true. Panel2 will not shrink/enlarge horizontally, which means Panel1 will not shrink/enlarge either. So, Panel1 is not autosized to the needed size for its children.

FAQ

see Autosize / Layout.