2010. november 4., csütörtök

How to draw an arrow into the header of a TDBGrid


Problem/Question/Abstract:

I'd like to draw a small arrow in the header cell of a DBGrid to indicate the sort order, but I can't find a way to do this.

Answer:

You need to override DBGrid.DrawCell method and for the heading to draw sorted arrows:

procedure TSMDBGrid.DrawCell(ACol, ARow: Longint; ARect: TRect; AState:
  TGridDrawState);
var
  TitleText: string;
  i, idxSort, BCol: LongInt;
  DrawFlag: Integer;
const
  intSortImageWidth: Integer = 7;
begin
  if (dgIndicator in Options) then
    BCol := ACol - 1
  else
    BCol := ACol;
  if (gdFixed in AState) and (ARow = 0) and (dgTitles in Options) and (ACol <> 0) then
  begin
    TitleText := Columns[BCol].Title.Caption;
    {draw a column sorted image}
    {look whether there is a sorting according this column}
    idxSort := -1;
    if (ARect.Right - ARect.Left > intSortImageWidth) then
    begin
      for i := 0 to SortColumns.Count - 1 do
        if (SortColumns[i].FieldName = Columns[BCol].FieldName) and
          (SortColumns[i].SortType <> stNone) then
        begin
          idxSort := i;
          break
        end;
      if idxSort > -1 then
        ARect.Right := ARect.Right - intSortImageWidth;
    end;
    {draw title.caption}
    if DefaultDrawing and (TitleText <> '') then
    begin
      Canvas.Brush.Style := bsClear;
      Canvas.Font := Columns[BCol].Title.Font;
      Canvas.Brush.Color := Columns[BCol].Title.Color;
      WriteTitleText(Canvas, ARect, 2, 2, TitleText, Columns[BCol].Title.Alignment);
      if idxSort > -1 then
      begin
        ARect.Right := ARect.Right + intSortImageWidth;
        i := (ARect.Bottom - ARect.Top - intSortImageWidth) div 2;
        if (SortColumns[idxSort].SortType = stAscending) then
        begin
          Canvas.Pen.Color := clBtnShadow;
          Canvas.MoveTo(ARect.Right - 4, ARect.Top + i);
          Canvas.LineTo(ARect.Right - 4 - intSortImageWidth, ARect.Top + i);
          Canvas.LineTo(ARect.Right - 4 - (intSortImageWidth div 2), ARect.Bottom -
            i);
          Canvas.Pen.Color := clBtnHighlight;
          Canvas.LineTo(ARect.Right - 4, ARect.Top + i);
        end
        else
        begin
          Canvas.Pen.Color := clBtnHighlight;
          Canvas.MoveTo(ARect.Right - 4 - (intSortImageWidth div 2), ARect.Top + i);
          Canvas.LineTo(ARect.Right - 4, ARect.Bottom - i);
          Canvas.LineTo(ARect.Right - 4 - intSortImageWidth, ARect.Bottom - i);
          Canvas.Pen.Color := clBtnShadow;
          Canvas.LineTo(ARect.Right - 4 - (intSortImageWidth div 2), ARect.Top + i);
        end;
      end;
    end;
  end
  else
    { ... }

Nincsenek megjegyzések:

Megjegyzés küldése