Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of font of TStringGrid's cell

I need to change the text color in a cell of TStringGrid in Delphi.

Just a cell. How can I do that?

like image 379
user980115 Avatar asked Nov 07 '11 22:11

user980115


1 Answers

You could use the DrawCell event to draw the cell content yourself.

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;

(Inspired by this.)

like image 171
Heinrich Ulbricht Avatar answered Nov 20 '22 12:11

Heinrich Ulbricht