【发布时间】:2011-12-24 00:31:16
【问题描述】:
我需要在 Delphi 中更改 TStringGrid 单元格中的文本颜色。
只是一个单元格。我该怎么做?
【问题讨论】:
标签: delphi colors delphi-xe tstringgrid
我需要在 Delphi 中更改 TStringGrid 单元格中的文本颜色。
只是一个单元格。我该怎么做?
【问题讨论】:
标签: delphi colors delphi-xe tstringgrid
您可以使用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.)
【讨论】:
ACol 和 ARow 参数仅更改一个单元格(也许解释对 InflateRect 的调用 - 不过,作为建议,您不需要单独的 var;您可以直接将 Rect 传递给 InflateRect,因为它没有声明为 const)。
Rect。如果其他人正在更改它,他们应该在这样做之前阅读现有代码。 :) 不错的编辑 - 它使在搜索中找到此答案的 Delphi 新手的答案更加不言自明。回复:单元格颜色,您可以通过检查固定行和列并跳过它们来处理绘制默认外观,使用clWindow 和clWindowText(或clHighlight 和clHighlightText,取决于State),基本上是通过如果不绘制单元格,则仅调用 InflateRect 和 TextRect。