Add graphical bar to a StringGrid col

前端 未结 2 829
滥情空心
滥情空心 2020-12-19 08:26

Using Delphi 2010 and a TStringGrid component, I currently display five filds from a database query.

Here is a simplied example of what i am doing

//set up t

2条回答
  •  别那么骄傲
    2020-12-19 09:13

    Add the text to the cells like you normally would. But you have to draw those bars in the OnDrawCell event. Leave DefaultDrawing as is (True by default), and erase the already drawn cell text in those columns by filling it in advance:

    procedure TForm1.grdMainDrawCell(Sender: TObject; ACol, ARow: Integer;
      Rect: TRect; State: TGridDrawState);
    var
      Progress: Single;
      R: TRect;
      Txt: String;
    begin
      with TStringGrid(Sender) do
        if (ACol = 4) and (ARow >= FixedRows) then
        begin
          Progress := StrToFloatDef(Cells[ACol, ARow], 0) / 100;
          Canvas.FillRect(Rect);
          R := Rect;
          R.Right := R.Left + Trunc((R.Right - R.Left) * Progress);
          Canvas.Brush.Color := clNavy;
          Canvas.Rectangle(R);
          Txt := Cells[ACol, ARow] + '%';
          Canvas.Brush.Style := bsClear;
          IntersectClipRect(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom);
          Canvas.Font.Color := clHighlightText;
          DrawText(Canvas.Handle, PChar(Txt), -1, Rect, DT_SINGLELINE or
            DT_CENTER or DT_VCENTER or DT_END_ELLIPSIS or DT_NOPREFIX);
          SelectClipRgn(Canvas.Handle, 0);
          ExcludeClipRect(Canvas.Handle, R.Left, R.Top, R.Right, R.Bottom);
          Canvas.Font.Color := clWindowText;
          DrawText(Canvas.Handle, PChar(Txt), -1, Rect, DT_SINGLELINE or
            DT_CENTER or DT_VCENTER or DT_END_ELLIPSIS or DT_NOPREFIX);
          SelectClipRgn(Canvas.Handle, 0);
        end;
    end;
    

    Custom drawn bars in StringGrid

    For more options, you might consider this DrawStatus routine.

提交回复
热议问题