更改TStringGrid单元格的字体颜色

use*_*115 6 delphi colors tstringgrid delphi-xe

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

只是一个细胞.我怎样才能做到这一点?

Hei*_*cht 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;
Run Code Online (Sandbox Code Playgroud)

(灵感来自于此.)

  • @Ken我添加了一些解释和细胞检查.最初,我很想让"使用另一个提供更多格式化功能的组件"作为真正的答案,因为我发现自定义绘图总是有点危险,因为它可能会破坏原生的外观和感觉.最好是自定义所有细胞而不是冒险让其他细胞以某种方式看起来不同.关于Rect:我很谨慎.也许有人决定使用Rect将代码添加到方法的末尾,而不知道我对值所做的更改. (2认同)