【问题标题】:Change color of font of TStringGrid's cell更改 TStringGrid 单元格的字体颜色
【发布时间】:2011-12-24 00:31:16
【问题描述】:

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

只是一个单元格。我该怎么做?

【问题讨论】:

    标签: delphi colors delphi-xe tstringgrid


    【解决方案1】:

    您可以使用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.

    【讨论】:

    • +1。除了根据 Remy 的评论进行编辑之外:由于问题询问了特定的 cell,因此您可能应该展示如何使用 AColARow 参数仅更改一个单元格(也许解释对 InflateRect 的调用 - 不过,作为建议,您不需要单独的 var;您可以直接将 Rect 传递给 InflateRect,因为它没有声明为 const)。
    • @Ken 我添加了更多解释和单元格检查。最初,我很想给出“使用另一个提供更多格式化功能的组件”作为真正的答案,因为我发现自定义绘图总是有点危险,因为它可能会破坏原生的外观和感觉。自定义绘制所有单元格可能比冒其他单元格看起来不同的风险要好。关于 Rect:我很谨慎。也许有人决定使用 Rect 在方法的末尾添加代码,而没有意识到我对值所做的更改。
    • Heinrich,提问者在更改它时应该知道他们正在修改Rect。如果其他人正在更改它,他们应该在这样做之前阅读现有代码。 :) 不错的编辑 - 它使在搜索中找到此答案的 Delphi 新手的答案更加不言自明。回复:单元格颜色,您可以通过检查固定行和列并跳过它们来处理绘制默认外观,使用clWindowclWindowText(或clHighlightclHighlightText,取决于State),基本上是通过如果不绘制单元格,则仅调用 InflateRectTextRect
    • 嗯嗯。如果匆忙中事情是可能的,你不会相信;)
    • @Ken 主题怎么样?我们需要关心这个吗?
    猜你喜欢
    • 2016-02-21
    • 2011-09-23
    • 2015-03-22
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多