2008. április 21., hétfő

How to draw multiple columns in a TComboBox


Problem/Question/Abstract:

How to draw multiple columns in a TComboBox

Answer:

You can go with a custom drawn combo box:

unit Unit1;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, ExtCtrls;

type

  TDataRec = class(TObject)
  private
    Str1: string;
    Str2: string;
  end;

  TForm1 = class(TForm)
    DeleteListBox1: TListBox;
    Header1: THeader;
    Image1: TImage;
    ComboBox1: TComboBox;
    procedure FormCreate(Sender: TObject);
    procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
      State: TOwnerDrawState);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var
  i: integer;
  DataRec: TDataRec;
begin
  for i := 1 to 10 do
  begin
    DataRec := TDataRec.Create;
    with DataRec do
    begin
      Str1 := 'String1 ' + IntToStr(i);
      Str2 := 'String2 ' + IntToStr(i);
    end;
    ComboBox1.Items.AddObject('', DataRec);
  end;
end;

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
  State: TOwnerDrawState);
var
  S1, S2: string;
  TempRect: TRect;
begin
  S1 := TDataRec(ComboBox1.Items.Objects[Index]).Str1;
  S2 := TDataRec(ComboBox1.Items.Objects[Index]).Str2;
  ComboBox1.Canvas.FillRect(Rect);
  TempRect := Rect;
  TempRect.Right := Header1.SectionWidth[0];
  ComboBox1.Canvas.StretchDraw(TempRect, Image1.Picture.Graphic);
  Rect.Left := Rect.Left + 50;
  DrawText(ComboBox1.Canvas.Handle, PChar(S1), Length(S1), Rect, dt_Left or dt_VCenter);
  Rect.Left := Rect.Left + 100;
  DrawText(ComboBox1.Canvas.Handle, PChar(S1), Length(S1), Rect, dt_Left or dt_VCenter);
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése