本例效果图:


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.

posted on 2008-03-14 14:41  万一  阅读(5276)  评论(4编辑  收藏  举报