我想创建一个自定义控件(TRichEdit的后代).我只想在editfield上面添加一些文字.
我已经创建了自己的控件,并覆盖了构造函数,为标题创建了一个TLabel.它有效,但我的问题是:如何将标签移到richedit上面?当我设置Top:= -5时,标签开始变得令人失望.
这是构造函数的代码:
constructor TDBRichEditExt.Create(AOwner: TComponent);
begin
  inherited;
  lblCaption := TLabel.Create(self);
  lblCaption.Parent := parent;
  lblCaption.Caption := 'Header';
  lblCaption.Top := -5;
end;
我认为标签令人失望,因为richedit是父母.我试过了
lblCaption.Parent := self.parent;
为了使拥有richedit的表格成为父母 - 但这不起作用......
我怎么能实现这个目标?谢谢你们!
我认为标签令人失望,因为richedit是父母
这是错的.在您的代码中,它的父级是TLabel它的父级TDBRichEditExt,应该是它的父级.请注意,在一个方法中TDBRichEditExt,Parent并且Self.Parent是同一个东西.如果你想的母公司TLabel是TDBRichEditExt本身-这你就没有 -那么你应该设置   lblCaption.Parent := self;.
现在,如果父的TLabel是父的TDBRichEditExt,那么该Top属性TLabel指的是父的TDBRichEditExt,而不是TDBRichEditExt它自己.因此,如果a的父级TDBRichEditExt是a TForm,则Top := -5意味着TLabel将位于表单上边缘上方五个像素处.你的意思是
lblCaption.Top := Self.Top - 5;
但-5是一个太小的数字.你真正应该使用的是
lblCaption.Top := Self.Top - lblCaption.Height - 5;
此外,标签和Rich Edit之间的间距为5 px.
另外,你想
lblCaption.Left := Self.Left;
另一个问题
但这不起作用,因为在创建组件时,我认为尚未设置父组件.因此,您需要的是在更合适的时间进行标签的定位.此外,每次移动组件时都会移动标签,这非常重要!
TDBRichEditExt = class(TRichEdit)
private
  FLabel: TLabel;
  FLabelCaption: string;
  procedure SetLabelCaption(LabelCaption: string);
public
  constructor Create(AOwner: TComponent); override;
  procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override;
published
  LabelCaption: string read FLabelCaption write SetLabelCaption;
end;
procedure TDBRichEditExt.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  inherited;
  if not assigned(Parent) then
    Exit;
  FLabel.Parent := self.Parent;
  FLabel.Top := self.Top - FLabel.Height - 5;
  FLabel.Left := self.Left;
end;
细节
此外,当您隐藏时TDBRichEditExt,您也想要隐藏标签.因此你需要
protected
  procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED;
哪里
procedure TDBRichEditExt.CMVisiblechanged(var Message: TMessage);
begin
  inherited;
  if assigned(FLabel) then
    FLabel.Visible := Visible;
end;
同样对于Enabled属性,您还需要更新TLabel每次TDBRichEditExt更改其父级时的父级:
protected
  procedure SetParent(AParent: TWinControl); override;
同
procedure TDBRichEditExt.SetParent(AParent: TWinControl);
begin
  inherited;
  if not assigned(FLabel) then Exit;
  FLabel.Parent := AParent;
end;