Anchors设定在Delphi界面设计中的用处 - 癫狂编程

Anchors设定在Delphi界面设计中的用处

进行Delphi界面设计经常有要对一个窗口进行分块设计的情况。

一般习惯上是用Panel作为Layout容器对窗口页面进行切割组织,有时候为了更好的显示效果还要在Panel里面嵌套子Panel。再设定控件本身的Align属性基本就能达到一个比较满意的效果。

以前没有怎么接触过resize的界面设计,做的程序界面基本也都是固定尺寸的。最近几天打算研究一下界面设计,因为如果打算做一个比较好的软件或者应用,良好的界面设计就可以占尽先机。网上搜了搜可供参考的资料,大部分是Delphi2,Delphi3时代留下来的例程,好不容易找到几个Delphi7以后的界面参考,一打开就是缺少N个第3方控件,或者一个窗口上罗列了N多个Panel,N多个Popmenu......看的头晕目眩。

没办法,只好自己试验了,缺什么网上查什么,查不到就自己琢磨。再不就从DFW或者盒子的故纸堆里刨点东西出来。想做的界面例子很简单,有点类似于金山词霸或者灵格斯一类的典型字典查询界面。分块当然还是万变不离其宗的Panel,splitter。

窗口最大化的时候发现上面的edit老兄还坚持自己的身段(size)。这可不行啊。怎么才能让它随着窗口最大化或者parent panel尺寸变化一起改变呢?

能不编程绝不编程,这是我一贯的原则,把有限的脑力用到革命更需要的地方去。从自己脑子N年前的经验故纸堆里翻了一下,首先想到的是align变为alClient,结果edit的size是变了,height也变了,跟parent panel形成了唇亡齿寒的关系。勉强可以用,但从我这吹毛求疵的人看来是不行地。

去网上搜......

查到一位网友的建议,在form的onCreate事件中先记下parent panel控件原来的位置。然后窗口onResize的事件里根据parent panel的当前位置和重新计算edit的位置和大小。这样做看起来没问题地。但还是得编一点程序。且慢,再搜。

终于发现另一位网友的建议。设置什么Anchors属性为True,赶紧改了Edit的属性一试,果然不错!

习惯追根问底,看Online Help。

Use Anchors to ensure that a control maintains its current position relative to an edge of its parent, even if the parent is resized. When its parent is resized, the control holds its position relative to the edges to which it is anchored.

If a control is anchored to opposite edges of its parent, the control stretches when its parent is resized. For example, if a control has its Anchors property set to [akLeft, akRight], the control stretches when the width of its parent changes.

Anchors is enforced only when the parent is resized. Thus, for example, if a control is anchored to opposite edges of a form at design time and the form is created in a maximized state, the control is not stretched because the form is not resized after the control is created.

这下明白了,edit的parent control是panel,如果Anchors的left,top,right,bottom都设置为True,那么子控件离父控件四个角的距离保持不变,你可以想象一个子控件被父控件五马分尸的感觉。说的有点惨了。注意一定要注意子控件的Parent是谁,如果是Form,你可以想象一张脸盆那么大的大脸。

就是一个单纯的控件属性设置,没有代码。但我想在界面设计中应该是应用广泛。

另外本人其实是非常严肃严谨的人,偶尔会调侃几句,此文行文方式不是我的本来风格。