首页 > 解决方案 > Delphi 自定义组件,拖动时无法在设计器中定位(顶部/左侧属性的自定义设置器)

问题描述

我写了一个组件,它绘制以 X,Y 为中心的图片。在运行时,组件随SetXY(X,Y: integer)过程移动。

为了实现这一点,我计算了绘制程序中的Left和值并相应地设置它们。Top所有这些都很好。

但是当我尝试在设计时进行初始定位时,我无法通过将组件拖动到所需位置来定位组件。

当我通过对象检查器设置LeftorTop属性时,它可以工作。

procedure MyCustomComponent.SetTop(const Value: integer);
begin
  if Top = (Value) then
    exit;
    
  inherited Top := Value;
  if csDesigning in ComponentState then
    FY := Value + FBmp.Width div 2;
  Invalidate;
end;
    
procedure MyCustomComponent.SetLeft(const Value: integer);
begin
  if Left = (Value) then
    exit;
    
  inherited Left := Value;
  if csDesigning in ComponentState then
    FX := Value + FBmp.Width div 2;
  Invalidate;
end;

我怀疑当组件在窗体上的设计时拖放时,它实际上并没有设置LeftTop公共属性,而是调用一些其他函数来设置我继承组件的基础控件的私有字段成员( TGraphicControl)。

标签: delphivcl

解决方案


正如 fpiette 和 Remy 都指出的那样,覆盖SetBounds就可以了。在设计时通过拖放组件定位组件时,它不会单独设置公共LeftTop属性。而是调用该SetBounds过程。

procedure MyComponent.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  inherited;
  if csDesigning in ComponentState then begin
    FX := ALeft + FBmp.Width div 2;
    FY := ATop + FBmp.Height div 2;
  end;
end;

编辑:

经过测试,我发现要在运行时将组件正确放置在表单上,​​您还必须检查csLoading组件状态。

所以一个更完整的解决方案是这样的:

procedure MyComponent.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  inherited;
  if (csDesigning in ComponentState) or (csLoading in ComponentState ) then begin
    FX := ALeft + FBmp.Width div 2;
    FY := ATop + FBmp.Height div 2;
  end;
end;

推荐阅读