本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, ComCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure TreeVIEw1Expanded(Sender: TObject; Node: TTreeNode);
procedure TreeVIEw1Collapsed(Sender: TObject; Node: TTreeNode);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
stream: TStream;
node: TTreeNode;
begin
TreeVIEw1.Align := alLeft;
stream := TMemoryStream.Create;
with TStringList.Create do begin
Add('一連長');
Add(' 一排長');
Add(' 一班長');
Add(' 戰士1');
Add(' 戰士2');
Add(' 戰士3');
Add(' 戰士4');
Add(' 二班長');
Add(' 三班長');
Add(' 二排長');
Add(' 三排長');
Add('二連長');
Add('三連長');
SaveToStream(stream);
Free;
end;
stream.Position := 0;
TreeVIEw1.LoadFromStream(stream);
stream.Free;
{指定圖像列表}
TreeVIEw1.Images := ImageList1;
{初始化圖標}
for node in TreeVIEw1.Items do
begin
if node.HasChildren then begin
Node.ImageIndex := 0;
Node.SelectedIndex := 0;
end else begin
node.ImageIndex := 2;
node.SelectedIndex := 3;
end;
end;
end;
{閉合時}
procedure TForm1.TreeVIEw1Collapsed(Sender: TObject; Node: TTreeNode);
begin
Node.ImageIndex := 0;
Node.SelectedIndex := 0;
end;
{展開時}
procedure TForm1.TreeVIEw1Expanded(Sender: TObject; Node: TTreeNode);
begin
Node.ImageIndex := 1;
Node.SelectedIndex := 1;
end;
end.
通過 StateImages、StateIndex 可以再添加一個狀態圖標, 譬如:
比上面的程序多了兩行代碼:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, ComCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure TreeVIEw1Expanded(Sender: TObject; Node: TTreeNode);
procedure TreeVIEw1Collapsed(Sender: TObject; Node: TTreeNode);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
stream: TStream;
node: TTreeNode;
begin
TreeVIEw1.Align := alLeft;
stream := TMemoryStream.Create;
with TStringList.Create do begin
Add('一連長');
Add(' 一排長');
Add(' 一班長');
Add(' 戰士1');
Add(' 戰士2');
Add(' 戰士3');
Add(' 戰士4');
Add(' 二班長');
Add(' 三班長');
Add(' 二排長');
Add(' 三排長');
Add('二連長');
Add('三連長');
SaveToStream(stream);
Free;
end;
stream.Position := 0;
TreeVIEw1.LoadFromStream(stream);
stream.Free;
TreeVIEw1.Images := ImageList1;
{多添加了下面兩行}
TreeVIEw1.StateImages := ImageList1;
TreeVIEw1.Items[0].StateIndex := 4; {使用 ImageList1 中的第五個圖標}
for node in TreeVIEw1.Items do
begin
if node.HasChildren then begin
Node.ImageIndex := 0;
Node.SelectedIndex := 0;
end else begin
node.ImageIndex := 2;
node.SelectedIndex := 3;
end;
end;
end;
procedure TForm1.TreeVIEw1Collapsed(Sender: TObject; Node: TTreeNode);
begin
Node.ImageIndex := 0;
Node.SelectedIndex := 0;
end;
procedure TForm1.TreeVIEw1Expanded(Sender: TObject; Node: TTreeNode);
begin
Node.ImageIndex := 1;
Node.SelectedIndex := 1;
end;
end.