Re: coloured text in stringgrid

Posted by Johan p14205 on July 18, 2007

In Reply to coloured text in stringgrid posted by coxy on July 17, 2007

: I am looking for help with stringgrids.
: I need to be able to put different coloured strings *within a cell*. So, for example, if I have the text "2 3" in a cell I would like the 2 to be black and the 3 to be white. I have looked everywhere for an answer, and unfortunately my skills are not up to solving this problem.

In the StringGrid.OnDrawCell event, replace what Delphi would output with your own stuff. Use StringGrid.Canvas.TextOut(L, T, S) with:
L = left position
T = top position
S = the text that you want to show

The trick: before each TextOut, calculate the left position and set the StringGrid.Canvas.Font properties as desired (color, but also style, size and font name can be set). If you want to output 3 strings in a different color:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
  with StringGrid1.Canvas do begin
    L := Rect.Left + 2;
    Font.Color := clRed;
    TextOut(L, Rect.Top + 2, S1);
    L := L + TextWidth(S1);
    Font.Color := clGreen;
    TextOut(L, Rect.Top + 2, S2);
    L := L + TextWidth(S1 + S2);
    Font.Color := clBlue;
    TextOut(L, Rect.Top + 2, S3);

S1, S2 and S3: extract from the text string that Delphi would normally show, available in StringGrid1.Cells[ACol, ARow].

Related articles

Annoying StringGrid Focus
... setting the focus on the upper lefthand cell [0,0] and coloring it dark blue. This obfuscates what i want to show in that cell...
Change cell colours
How to set up arrays for FG and BG colours of stringgrid cells
Coloured text in stringgrid
Put differently coloured strings *within one cell*: part 1 red, part 2 blue,...

Follow Ups