Delphi 自定义组件,拖动时无法在设计器中定位(Top/Left 属性的自定义设置器)

杰佩·克劳森

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

为了实现这一点,我计算了绘制例程中LeftTop值应该是什么,相应地设置它们。所有这些都很好。

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

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

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;

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

杰佩·克劳森

正如 fpiette 和 Remy 所指出的,覆盖 theSetBounds就成功了。在设计时通过拖放组件定位组件时,它不会单独设置公共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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章