我尝试使用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;
Run Code Online (Sandbox Code Playgroud)
在构造函数中定义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;
Run Code Online (Sandbox Code Playgroud)
定义更改边框颜色和宽度的过程
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;
Run Code Online (Sandbox Code Playgroud)
但是,当我将组件放在窗体上时,Shape不会被绘制.我的代码中的错误在哪里?
TShape是一个TGraphicControl派生控件,因此它永远不会出现在TWinControl除了它自己之外的派生控件之上Parent.
您的TGEdit构造函数中包含错误. Self.Parent是在构造函数为零,所以你分配一个零Parent的TShape,因此它永远不会是可见的.
如果你想要与你TShape的相同Parent,TGEdit你需要覆盖虚拟SetParent()方法,该方法在构造完成后调用.您还必须覆盖虚拟SetBounds()方法,以确保在TShape移动时TGEdit移动,例如:
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;
Run Code Online (Sandbox Code Playgroud)
现在,尽管如此,还有另一种解决方案 - 从中派生您的组件TCustomPanel并让它自己创建TEdit.您可以根据需要设置面板的颜色,边框等.
| 归档时间: |
|
| 查看次数: |
3065 次 |
| 最近记录: |