【问题标题】:A Delphi Custom Control: A TRichEdit with a TLabel Above ItDelphi 自定义控件:上面带有 TLabel 的 TRichEdit
【发布时间】:2011-03-04 01:31:53
【问题描述】:

我想创建一个自定义控件(TRichEdit 的后代)。 我只是想在编辑字段上方添加一些文本。

我创建了自己的控件,并重写了构造函数来为标题创建一个 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的表单成为父级-但这不起作用...

我怎样才能做到这一点? 谢谢大家!

【问题讨论】:

  • 您是否查看过 ExtCtrls 单元中的TLabeledEdit 控件?它应该准确地告诉你如何做你所追求的。
  • 罗布·肯尼迪是对的。 TLabeledEdit 是一个 TEdit,上面有一个 TLabel。这是此过程的标准示例。阅读源代码并学习。如果您需要更多解释,请阅读下面的答案(另外)。

标签: delphi controls


【解决方案1】:

我认为标签是合乎逻辑的 消失,因为 Richedit 是 父母

这是错误的。在您的代码中,TLabel 的父级应该是TDBRichEditExt 的父级。请注意,在TDBRichEditExtParentSelf.Parent 的方法中是同一件事。 如果您希望TLabel 的父级是TDBRichEditExt 本身 - 您这样做 - 那么您应该设置lblCaption.Parent := self;

现在,如果TLabel 的父级是TDBRichEditExt 的父级,那么TLabelTop 属性指的是TDBRichEditExt 的父级,而不是TDBRichEditExt 本身。因此,如果TDBRichEditExt 的父级是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;

另一个问题

但这不起作用,因为在创建组件时,我认为还没有设置 Parent。因此,您需要在更合适的时间进行标签的定位。另外,这会在你的组件每次移动时移动标签,这一点非常重要!

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 属性也是如此,每次TDBRichEditExt 的父级更改时,您还需要更新TLabel 的父级:

protected
  procedure SetParent(AParent: TWinControl); override;

procedure TDBRichEditExt.SetParent(AParent: TWinControl);
begin
  inherited;
  if not assigned(FLabel) then Exit;
  FLabel.Parent := AParent;
end;

【讨论】:

  • 很好的答案,非常感谢您提供如此详细的信息以及您为解释它所做的努力!
  • 它的内容比 Andreas 解释的要多(很好,必须说 +1),请参阅 ExtCtrls.pas 中的 TLabeledEdit 源代码。例如,表单通知处理。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2012-11-19
相关资源
最近更新 更多