本例效果圖:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Grids, ExtCtrls;
type
TForm1 = class(TForm)
TreeView1: TTreeVIEw;
Memo1: TMemo;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{初始化 TreeVIEw1}
procedure TForm1.FormCreate(Sender: TObject);
var
Nodes: TTreeNodes;
node: TTreeNode;
begin
TreeVIEw1.Align := alLeft;
Nodes := TreeVIEw1.Items;
node := Nodes.Add(nil, '一連長');
node := Nodes.AddChild(node, '一排長');
node := Nodes.AddChild(node, '一班長');
node := Nodes.AddChild(node, '戰士1');
Nodes.Add(node, '戰士2');
Nodes.Add(node, '戰士3');
Nodes.Add(node, '戰士4');
node := node.Parent;
Nodes.Add(node, '二班長');
Nodes.Add(node, '三班長');
node := node.Parent;
Nodes.Add(node, '二排長');
Nodes.Add(node, '三排長');
node := node.Parent;
Nodes.Add(node, '二連長');
Nodes.Add(node, '三連長');
end;
{保存到文件}
procedure TForm1.Button1Click(Sender: TObject);
const
path = 'c:\temp\tree.txt';
begin
TreeVIEw1.SaveToFile(path);
TButton(Sender).Caption := '保存';
end;
{從文件中載入}
procedure TForm1.Button2Click(Sender: TObject);
const
path = 'c:\temp\tree.txt';
begin
if FileExists(path) then TreeVIEw1.LoadFromFile(path);
TButton(Sender).Caption := '載入';
end;
{從流中讀取}
procedure TForm1.Button3Click(Sender: TObject);
var
stream: TStream;
begin
stream := TMemoryStream.Create;
try
Memo1.Lines.SaveToStream(stream);
stream.Position := 0;
TreeVIEw1.LoadFromStream(stream);
finally
stream.Free;
end;
end;
end.
注意: 上面例子中的"從流中讀取"部分, 對 Memo 中的數據格式有嚴格要求, 要求必須是樹狀結構;
結構中可以用"空格"和"Tab"分層.