RobertFrank
RobertFrank

Reputation: 7394

Is TLabel.Font := TDbGrid.Font safe if later I do TLabel.Free

I have some TLabels that I want to have the same font as a grid that is always visible.

Some of the TLabels are dynamically created at runtime:

 Label1 := TLabel.Create(Self);
 Label1.Name := 'MyLabel';
 Label1.Parent := SomeOtherPersisentLabelOnForm.Parent;
 Label1.Left, Width, Height, Top := etc.
 Label1.Font := dbGrid.Font; 

Is the above Font assignment safe if later I do:

 Label1.Free;

Or will Label1.Free dispose of its owned Font object in such a way that the grid's Font property is pointing to nothing?

If it's unsafe, is

Label1.Font.Assign(SomeOtherPersisentLabelOnForm.Font);

how to do it?

Upvotes: 0

Views: 81

Answers (2)

Mason Wheeler
Mason Wheeler

Reputation: 84640

TLabel gets its Font property from TControl, and TControl.SetFont() is not virtual, so this should hold true for every VCL control.

procedure TControl.SetFont(Value: TFont);
begin
  FFont.Assign(Value);
end;

So yeah, it's safe.

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 613382

Label1.Font := dbGrid.Font; 

The implementation of the setter for the Font property of TLabel takes a copy of the other font, rather than a reference. So, you can regard this as having the semantics of a value assignment.

The property setter is in fact declared in TControl and looks like this:

procedure TControl.SetFont(Value: TFont);
begin
  FFont.Assign(Value);
end;

So, it is perfectly save to destroy either of the two fonts because there are indeed two unrelated instances, one in each control.

You'll find this pattern throughout the VCL for properties like fonts, pens, brushes etc.

Upvotes: 3

Related Questions