【发布时间】:2011-06-27 04:43:06
【问题描述】:
我有一个使用 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.
【问题讨论】:
-
我的所有控件都使用其父控件的字体。这显然是它的工作方式。为什么你的控件行为不端?我不知道。也许故障的最小再现会有所帮助。
标签: delphi fonts components delphi-5