我有一个源自 TGraphicControl 的自定义 Delphi 组件。它的类声明如下:
TMyLabel = class(TGraphicControl)
private
...
protected
...
public
...
published
property Height;
property Width write SetWidth;
...
end;
SetWidth 的实现更进一步:
procedure TMyLabel.SetWidth(const Value: Integer);
begin
if (Value >= 0) and (Value <> Width)
then begin
inherited Width := Value;
// Do some other stuff
...
end;
MessageDlg('Test', mtInformation, [mbOK], 0);
end;
当前,当在运行时或设计时通过在对象检查器的相应字段中输入值以编程方式更改组件的宽度时,我会调用 SetWidth。但是,当我在设计时使用鼠标调整组件大小时,对象检查器“宽度”字段会更新,但不会显示消息框,因此不会调用我的 SetWidth 过程。
我需要在鼠标调整组件大小时调用 SetWidth,以便我可以为 Paint 过程设置一个标志,以了解它何时必须执行其他操作(除了重新绘制组件之外)。有没有办法实现这一点?
最佳答案
同时Mason Wheeler's answer这是您问题的答案,我想警告您。
重写属性可能会产生奇怪的结果,因为您不能拥有“虚拟”属性,并且 SetWidth 也不是虚拟的。如果有人使用您的类的后代来设置 Width 属性,则不会调用您的代码。因此我建议不要以这种方式覆盖属性。
var Control: TControl;
begin
Control := MyLabel;
Control.Width := 5000; // TMyLabel.SetWidth is not called!!
此外:设置 Width 属性并不是更改控件宽度的唯一方法,如 Deltics explains 。您应该重写 TControl.SetBounds。
var MyLabel: TMyLabel;
begin
MyLabel.SetBounds(0, 0, 100, 100); // TMyLabel.SetWidth nor TControl.SetWidth is called!!
但是您似乎想限制控件的宽度。然后你最好覆盖为此目的而制作的TControl.CanResize。或者,如果您只想对任何类型的调整大小使用react,最好重写TControl.Resize。
关于delphi - 重新声明自定义 Delphi 组件的 Width 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4251324/