本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure TreeVIEw1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{我隨意地使用了不同的方法去動態添加數據}
procedure TForm1.FormCreate(Sender: TObject);
var
stream: TMemoryStream;
begin
TreeVIEw1.Align := alLeft;
stream := TMemoryStream.Create;
with TStringList.Create do
begin
Add('一連長');
Add(#9+'一排長');
Add(#9+#9+'一班長');
Add(#9+#9+#9+'戰士1');
Add(#9+#9+#9+'戰士2');
Add(#9+#9+#9+'戰士3');
Add(#9+#9+#9+'戰士4');
Add(#9+#9+'二班長');
Add(#9+#9+'三班長');
Add(#9+'二排長');
Add(#9+'三排長');
Add('二連長');
Add('三連長');
SaveToStream(stream);
Free;
end;
stream.Position := 0;
TreeVIEw1.LoadFromStream(stream);
stream.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
TreeVIEw1.FullExpand;
(Sender as TButton).Caption := '全部展開';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
TreeVIEw1.FullCollapse;
(Sender as TButton).Caption := '全部關閉';
end;
procedure TForm1.TreeVIEw1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
node: TTreeNode;
begin
if Boolean(TreeVIEw1.GetNodeAt(X,Y)) then
begin
node := TreeVIEw1.GetNodeAt(X,Y);
Text := node.Text;
end;
end;
end.