我有一个使用ParentFont
.
在构建组件期间,我可以看到最初组件的字体设置为默认值MS Sans Serif
:
constructor TCustomWidget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
...
end;
检查节目Self.Font.Name: 'MS Sans Serif'
一段时间后,我的组件的字体会更新以反映父级的字体:
TReader.ReadComponent(nil)
SetCompName
TControl.SetParentComponent
TControl.SetParent
TWinControl.InsertControl
AControl.Perform(CM_PARENTFONTCHANGED, 0, 0);
之后一切都很好,我的组件的字体已更改为父字体(例如`MS Shell Dlg 2')。
问题是我的子控件与它们父控件的字体(即我的组件)不同步。
在我的组件构造函数中,我创建了子控件:
constructor TCustomWidget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
...
CreateComponents;
end;
procedure TCustomWidget.CreateComponents;
begin
...
FpnlBottom := TPanel.Create(Self);
FpnlBottom.Caption := '';
FpnlBottom.Parent := Self;
FpnlBottom.Align := alBottom;
FpnlBottom.Height := 46;
FpnlBottom.ParentFont := True;
...
end;
最初我FpnlBottom
也有默认字体MS Sans Serif
。
稍后,当我的组件的字体已更新为其父字体(例如MS Shell Dlg 2
)时,子控件没有更新其字体,而是保持MS Sans Serif
.
- 为什么我的子控件的
ParentFont
财产没有得到尊重? - 如何使我的子控件的
ParentFont
属性起作用?
示例代码
工具两个小时将其精简为可管理、可重现的代码:
unit WinControl1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls;
type
TWidget = class(TWinControl)
private
FTitleLabel: Tlabel;
FpnlBottom: TPanel;
procedure CreateComponents;
protected
procedure FontChange(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
published
{Inherited from TWinControl}
property Align;
property Font;
property ParentFont;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples',[TWidget]);
end;
{ TCustomWidget }
constructor TWidget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csAcceptsControls, csNoDesignVisible];
Self.Width := 384;
Self.Height := 240;
Self.Font.OnChange := FontChange;
CreateComponents;
end;
procedure TWidget.CreateComponents;
begin
FpnlBottom := TPanel.Create(Self);
FpnlBottom.Parent := Self;
FpnlBottom.Align := alBottom;
FpnlBottom.Color := clWindow;
FpnlBottom.Caption := 'FpnlBottom';
FpnlBottom.Height := 45;
FTitleLabel := TLabel.Create(Self);
FTitleLabel.Parent := FpnlBottom;
FTitleLabel.Left := 11;
FTitleLabel.Top := 11;
FTitleLabel.Caption := 'Hello, world!';
FTitleLabel.AutoSize := True;
FTitleLabel.Font.Color := $00993300;
FTitleLabel.Font.Size := Self.Font.Size+3;
FTitleLabel.ParentFont := False;
end;
procedure TWidget.FontChange(Sender: TObject);
begin
//title label is always 3 points larger than the rest of the content
FTitleLabel.Font.Name := Self.Font.Name;
FTitleLabel.Font.Size := Self.Font.Size+3;
OutputDebugString(PChar('New font '+Self.Font.Name));
end;
end.