You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TStringGrid选中行单元格左侧出现异色矩形的问题求助

解决TStringGrid选中行高亮时左侧出现深蓝色矩形的问题

我之前也碰到过一模一样的问题!那个左侧的小蓝块其实是TStringGrid自带的行选择指示器——就是用来标记选中行的左侧窄列。你的代码只处理了普通单元格(ACol≥0的情况)的绘制逻辑,但完全没管这个特殊的指示器列(对应ACol = -1),所以系统还是用默认样式绘制了它,就出现了这个违和的蓝色矩形。

给你两个实用的解决思路,按需选择就行:

方案1:直接隐藏行指示器列

如果根本不需要这个指示器,直接把它关掉最省事。在窗体初始化的代码里(比如FormCreate事件)加上这一行:

testGrid.Options := testGrid.Options - [goIndicator];

执行后左边的指示器列会直接消失,自然不会有蓝色块困扰你了。

方案2:自定义绘制行指示器列

要是想保留指示器的位置,让它和高亮行的样式统一,那就修改你的DrawCell代码,加上对ACol=-1的处理:

procedure TTestForm.testGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  // 先处理行指示器列(ACol=-1)
  if ACol = -1 then
  begin
    testGrid.Canvas.Pen.Color := clNone;
    // 和选中行背景色保持一致
    testGrid.Canvas.Brush.Color := IfThen(ARow = SelectedRow, clActiveCaption, clWindow);
    testGrid.Canvas.Rectangle(Rect);
    Exit; // 指示器列不需要绘制文本,直接退出
  end;

  // 处理普通单元格的逻辑
  testGrid.Canvas.Pen.Color := clNone;
  testGrid.Canvas.Brush.Color := IfThen(ARow <> SelectedRow, clWindow, clActiveCaption);
  
  // 记得恢复默认字体颜色,不然红色会影响其他行
  if ColorTSTringList[ARow] = 'Red' then
    testGrid.Canvas.Font.Color := clRed
  else
    testGrid.Canvas.Font.Color := clWindowText;

  testGrid.Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom);
  testGrid.Canvas.TextRect(Rect, Rect.Left, Rect.Top, testGrid.Cells[ACol,ARow]);
end;

另外提醒下,你原来的代码没恢复字体颜色,要是某一行设了红色,后面的行可能会跟着变红色,所以一定要加个else分支把字体颜色改回默认的clWindowText。

内容的提问来源于stack exchange,提问作者user2814916

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:42:44