I need to change the text color in a cell of TStringGrid
in Delphi.
Just a cell. How can I do that?
I need to change the text color in a cell of TStringGrid
in Delphi.
Just a cell. How can I do that?
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.)
Rect
. If someone else is changing it, they should be reading the existing code before doing so. :) Nice edits - it makes the answer more self-explanatory to someone new to Delphi that finds this answer in a search. Re: cell color, you can handle drawing the default look by checking for fixed rows and cols and skipping them, using clWindow
and clWindowText
(or clHighlight
and clHighlightText
depending on State
), and basically by calling only InflateRect
and TextRect
if the cell is NOT to be drawn. –
Chorus clWindow
and clWindowText
system colors; changes in theme colors should be handled for you, and the default drawing without changing anything should handle the rest. I have a full example of drawing a TStringGrid
with a right-aligned column for monetary values I use at work that responds to theming just fine, and it's a dozen lines of code or so. Wasn't suggesting custom-drawing your own grid all the time; if you need that, a custom component is better. –
Chorus © 2022 - 2024 — McMap. All rights reserved.
ACol
andARow
parameters (and maybe explain the call toInflateRect
- as a suggestion, though, you don't need a separate var; you can directly passRect
toInflateRect
, since it's not declared as aconst
). – Chorus