我正在将delphi 2010用于具有stringgrid的项目。我希望网格的某些列是正确的。 I understand how I can do this,其中defaultdrawing设置为false。

但是,我希望尽可能保留网格的运行时主题阴影。有没有一种方法可以使启用了defaultdrawing的列右对齐,或者至少重复onDrawCell事件中的代码以模仿运行时主题着色?

最佳答案

您可以使用插入器类并重写DrawCell方法,请检查此示例

type
  TStringGrid = class(Grids.TStringGrid)
   protected
    procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
  end;

  TForm79 = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
  private
  end;

var
  Form79: TForm79;

implementation

{$R *.dfm}

{ TStringGrid }

procedure TStringGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState);
var
  s : string;
  LDelta : integer;
begin
  if (ACol=1) and (ARow>0) then
  begin
    s     := Cells[ACol, ARow];
    LDelta := ColWidths[ACol] - Canvas.TextWidth(s);
    Canvas.TextRect(ARect, ARect.Left+LDelta, ARect.Top+2, s);
  end
  else
  Canvas.TextRect(ARect, ARect.Left+2, ARect.Top+2, Cells[ACol, ARow]);
end;

procedure TForm79.FormCreate(Sender: TObject);
begin
  StringGrid1.Cells[0,0]:='title 1';
  StringGrid1.Cells[1,0]:='title 2';
  StringGrid1.Cells[2,0]:='title 3';

  StringGrid1.Cells[0,1]:='normal text';
  StringGrid1.Cells[1,1]:='right text';
  StringGrid1.Cells[2,1]:='normal text';
end;


结果

09-25 19:46
查看更多