更改TStringGrid单元格的字体颜色

时间:2011-11-07 22:33:41

标签: delphi colors delphi-xe tstringgrid

我需要在Delphi的TStringGrid单元格中更改文本颜色。

只是一个细胞。我怎么能这样做?

1 个答案:

答案 0 :(得分:12)

您可以使用DrawCell事件自行绘制单元格内容。

procedure TForm1.GridDrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  S: string;
  RectForText: TRect;
begin
  // Check for your cell here (in this case the cell in column 4 and row 2 will be colored)
  if (ACol = 4) and (ARow = 2) then
  begin
    S := Grid.Cells[ACol, ARow];
    // Fill rectangle with colour
    Grid.Canvas.Brush.Color := clBlack;
    Grid.Canvas.FillRect(Rect);
    // Next, draw the text in the rectangle
    Grid.Canvas.Font.Color := clWhite;
    RectForText := Rect;
    // Make the rectangle where the text will be displayed a bit smaller than the cell
    // so the text is not "glued" to the grid lines
    InflateRect(RectForText, -2, -2);
    // Edit: using TextRect instead of TextOut to prevent overflowing of text
    Grid.Canvas.TextRect(RectForText, S);
  end;
end;

(灵感来自this.