2006. június 26., hétfő

Use a TProgressbar within a TListbox


Problem/Question/Abstract:

How to use a TProgressbar within a TListbox

Answer:

It is possible, but you have to tie the TProgressBar to the listbox at runtime, the listbox will not accept a component dropped on it as child. Create a new project, drop a TButton, TListbox, TProgressbar, TTimer on it. Set the timers Interval to 100, its Enabled property to false. Attach handlers to the Timers OnTimer and buttons onClick event, complete as below:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
  Forms, Dialogs, stdctrls, ExtCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    ProgressBar1: TProgressBar;
    Timer1: TTimer;
    procedure Timer1Timer(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  progressbar1.StepIt;
  if progressbar1.Position >= progressbar1.Max then
    timer1.enabled := false;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
begin
  if timer1.Enabled then
    exit;
  listbox1.clear;
  for i := 1 to 20 do
    listbox1.Items.add(Format('Item %d', [i]));
  progressbar1.Position := progressbar1.Min;
  if progressbar1.Parent <> listbox1 then
  begin
    progressbar1.Parent := listbox1;
    progressbar1.BoundsRect := listbox1.ItemRect(2);
  end;
  timer1.enabled := true;
end;

end.

Build and run, click the button.

Nincsenek megjegyzések:

Megjegyzés küldése