2

我将 delphi 2010 用于带有 stringgrid 的项目。我希望网格的某些列是右对齐的。我了解如何通过将 defaultdrawing 设置为 false 来做到这一点。

但是,如果可能的话,我想为网格保留运行时主题着色。有没有办法在启用 defaultdrawing 的情况下右对齐列,或者至少复制 onDrawCell 事件中的代码以模仿运行时主题着色?

4

1 回答 1

7

您可以使用插入器类并覆盖 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;

结果

在此处输入图像描述

于 2012-04-07T03:15:52.487 回答