Friday, 29 August 2014

Difference between Owner and Parent in Delphi

Difference between Owner and Parent in Delphi

Parent is the Window control where the control is displayed. Owner is the component responsible for making sure it's destroyed. Parent refers to the component that another component is contained in, such as TForm, TGroupBox or a TPanel. If one control (parent) contains others, the contained controls are child controls of the parent.

Example of Owner and Parent

Whenever we try add a button on a panel in a form, we try to make an invisible connection between the components. When a component is dropped on a form at design time, the owner is the form and the parent is the container on which it is dropped.

As we add the button on the panel, the panel automatically is set as the parent of the button while the form becomes the owner.  

Another example, drop a group box on a form. Its owner and parent are both the form. Drop a check box on the group box. Its owner is the form and its parent is the group box.

Parent is required to make a control visible

For a component to be visible, it must have a parent to display itself within. Controls that appear on the screen need to know where to paint themselves, hence the parent property. It specifies the visual container for the control. This property must be specified before a control can be displayed. When you want to create a TButton at run-time, it is important that we remember to assign a parent - the control that contains the button. 

The Parent component on the other end determines how the child (i.e. contained component is to be displayed). All the properties like left, top etc are relative to the parent component.

Owner is Readonly while Parent can be changed

Owner property is a read only property and cannot be modified, however parent for a control can be assigned and chagned easily at runtime. The Owner is being set while invoking the create constructor and becomes a read-only property so can't be changed later on.

Allocating and Freeing the memory

The Owner component is responsible for freeing the allocated memory of the owned components. Form is the owner of all the components residing inside it. So whenever the form is destroyed, all the components memory is freed automatically. This is the purpose of ownership.

HasParent Property

Not all components have the Parent. Many forms do not have a Parent. For example, forms that appear directly on the Windows desktop have Parent set to nil. A component's HasParent method returns a boolean value indicating whether or not the component has been assigned a parent.

Parent Property

We use the Parent property to get or set the parent of a control. If we try to create a new control, then we need to set the parent property of the control to make it visible. For example, 

Button1.Parent := Panel1;

Above code has set Panel1 as the parent of Button1.

No comments:

Post a Comment