gpt4 book ai didi

delphi - 如何使用 TShape 在编辑字段周围绘制彩色边框?

转载 作者:行者123 更新时间:2023-12-01 22:29:33 27 4
gpt4 key购买 nike

我尝试使用 TShape 在 TEdit 字段周围绘制彩色边框。我定义了以下组件:

type TGEdit = class(TEdit)
private
m_shape : TShape;
protected
procedure setBorderColor( brd_col : TColor );
procedure setBorderWidth( brd_wid : integer );
public
constructor create(AOwner : TComponent); override;
destructor destroy(); override;
published
property borderColor : TColor read m_border_color write setBorderColor default clBlack;
property borderWidth : integer read m_border_width write setBorderWidth default 1;
end;

在构造函数中定义 TShape 对象。

constructor TGEdit.create(AOwner : TComponent);
begin
inherited;
Self.BorderStyle:= bsNone;
m_border_color := clBlack;
m_border_width := 1;
m_shape := TShape.Create(AOwner);
m_shape.Parent := Self.Parent;
m_shape.Shape := stRectangle;
m_shape.Width := Self.Width+2*m_border_width;
m_shape.Height := Self.Height+2*m_border_width;
m_shape.Left := Self.Left-m_border_width;
m_shape.Top := self.Top-m_border_width;
m_shape.Brush.Style := bsClear;
m_shape.Pen.Color := m_border_color;
m_shape.Pen.Style := psSolid;
end;

destructor TGNumberEdit.destroy();
begin
m_shape.Free();
inherited;
end;

定义一个改变边框颜色和宽度的过程

procedure TGEdit.setBorderColor( brd_col : TColor );
begin
if m_border_color = brd_col then
exit;
m_border_color := brd_col;
m_shape.Pen.Color := m_border_color;
end;

procedure TGEdit.setBorderWidth( brd_wid : integer );
begin
if (m_border_width = brd_wid) or (brd_wid < 0) then
exit;
m_border_width := brd_wid;
m_shape.Pen.Width := m_border_width;
end;

但是当我将组件放在表单上时,形状不会绘制。我的代码哪里有错误?

最佳答案

TShapeTGraphicControl 派生控件,因此永远不会出现在 TWinControl 派生控件之上,除了它自己的 父级

您的TGEdit构造函数中有一个错误。 Self.Parent 在构造函数中为 nil,因此您将 nil Parent 分配给 TShape,因此它永远不会可见。

如果您希望 TShape 与您的 TGEdit 具有相同的 Parent,那么您需要重写虚拟 SetParent() 方法,构造完成后调用。您还必须重写虚拟 SetBounds() 方法,以确保您的 TShapeTGEdit 移动而移动,例如:

type
TGEdit = class(TEdit)
...
protected
...
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetParent(AParent: TWinControl); override;
...
end;

procedure TGEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
if m_shape <> nil then
m_shape.SetBounds(Self.Left - m_border_width, Self.Top - m_border_width, Self.Width + (2*m_border_width), Self.Height + (2*m_border_width));
end;

procedure TGEdit.SetParent(AParent: TWinControl);
begin
inherited;
if m_shape <> nil then
m_shape.Parent := Self.Parent;
end;

现在,尽管如此,还有一个替代解决方案 - 从 TCustomPanel 派生您的组件,并让它在其自身之上创建一个 TEdit。您可以根据需要设置Panel的颜色、边框等。

关于delphi - 如何使用 TShape 在编辑字段周围绘制彩色边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21690403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com