首页 > 技术文章 > Delphi: TLabel设置EllipsisPosition属性用...显示过长文本时,以Hint显示其全文本

crwy 2018-05-03 09:29 原文

仍然是处理多语言中碰到问题。

Delphi自2006版以后,TLabel有了EllipsisPosition属性,当长文本超过其大小时,显示以...,如下图:

这样虽然解决显示问题,但很显然,不知道...究竟省略了什么。

 

于是就想:此类情况,能不能鼠标移上去,以Hint显示完全文本?

追踪其源代码,及查阅资料,实现了这个想法,扩充TLabel,代码如下:

声明:

type
  TLabel = class(StdCtrls.TLabel)
  protected
    procedure DoDrawText(var Rect: TRect; Flags: Longint); override;
  end;

实现:

{ TLabel }

procedure TLabel.DoDrawText(var Rect: TRect; Flags: Integer);
begin
  inherited;

  if (EllipsisPosition <> epNone) and not AutoSize and Assigned(Parent)
    and (not ShowHint or (Hint = ''))
    and (Canvas.TextWidth(Caption) > Width) then
  begin
    ShowHint := True;
    Hint := Caption;
  end;
end;

置此代码于所在单元中,或封装为一单独单元,引用在StdCtrls之后即可。

验证问题解决。却截不到图,有兴趣者可以自己试下。

 

参考资料:

How to create resize event for TLabel (TGraphicControl)

推荐阅读