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

Delphi中如何为TChart各系列柱状条显示鼠标悬停提示

解决TChart鼠标悬停显示对应柱状条数值的问题

问题场景

项目中有多个TChart控件,每个图表包含2个系列,每个系列有2个柱状条。需要实现鼠标悬停在任意柱状条上时,显示该条对应的数值。现有代码要么只能显示第一个系列的数值,添加循环后又仅能显示第二个系列的数值。

原代码问题分析

添加循环后的代码存在逻辑缺陷:遍历所有系列时,每次循环都会覆盖ShowHint和Hint的值。如果鼠标悬停在第一个系列的柱子上,循环到第二个系列时,clicked(X,Y)会返回-1,此时ShowHint会被设为false,同时Hint也会被覆盖,最终只保留最后一个系列的判断结果。

修复后的代码

单条柱状条提示(悬停哪条显示哪条)

procedure TfrmBoard.chartCountMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  SeriesIndex: Integer;
  i: Integer;
  CurrentChart: TChart;
begin
  CurrentChart := Sender as TChart;
  ShowHint := False;
  Hint := '';

  // 遍历所有系列,查找鼠标命中的柱状条
  for i := 0 to CurrentChart.SeriesCount - 1 do
  begin
    SeriesIndex := CurrentChart.Series[i].Clicked(X, Y);
    if SeriesIndex <> -1 then
    begin
      ShowHint := True;
      // 自定义提示文本,可添加系列名称
      Hint := Format('系列%d: %.2f', [i+1, CurrentChart.Series[i].YValues.Value[SeriesIndex]]);
      Break; // 找到命中系列后跳出循环,避免覆盖结果
    end;
  end;
end;

同位置多系列提示(并列柱状条时显示所有对应数值)

如果需要同时显示同一位置下两个系列的数值,可去掉Break,改为拼接提示文本:

procedure TfrmBoard.chartCountMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  SeriesIndex: Integer;
  i: Integer;
  CurrentChart: TChart;
begin
  CurrentChart := Sender as TChart;
  ShowHint := False;
  Hint := '';

  for i := 0 to CurrentChart.SeriesCount - 1 do
  begin
    SeriesIndex := CurrentChart.Series[i].Clicked(X, Y);
    if SeriesIndex <> -1 then
    begin
      ShowHint := True;
      if Hint <> '' then
        Hint := Hint + #13#10; // 换行分隔不同系列的数值
      Hint := Hint + Format('系列%d: %.2f', [i+1, CurrentChart.Series[i].YValues.Value[SeriesIndex]]);
    end;
  end;
end;

代码说明

  1. 先初始化ShowHint为false、Hint为空,避免残留之前的提示状态
  2. 遍历每个系列,调用Clicked(X,Y)判断鼠标是否命中当前系列的柱状条
  3. 命中后设置提示状态与文本,根据需求选择是否跳出循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:27:30