[code=Delphi(Pascal)] unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Menus;
type TAInfo = class private FID: integer; FPId: integer; FName: String; public constructor Create ; overload ; constructor Create(id:integer; pId :integer; name :String ) ; overload ;
public property ID :integer read FID write FID ; property PId :integer read FPId write FPId ; property Name :String read FName write FName ; end; TForm1 = class(TForm) tv1: TTreeView; pm1: TPopupMenu; N1: TMenuItem; procedure FormCreate(Sender: TObject); procedure N1Click(Sender: TObject); procedure tv1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject); var Node :TTreeNode ; info :TAInfo ; begin tv1.Items.BeginUpdate ; tv1.Items.Clear ;
tv1.Items.EndUpdate ; info := TAInfo.Create(1,0,'开发部'); Node := tv1.Items.Add(nil, info.Name) ; //1 Node.Data := info ; //2 // 1和2 可以用下面语句代替 // Node := tv1.Items.AddObject(nil, info.Name, info) ;
end;
{ TAInfo }
constructor TAInfo.Create; begin self.FID := 0 ; self.FPId := -1 ; self.FName := '' ; end;
constructor TAInfo.Create(id, pId: integer; name: String); begin self.FID := id ; self.FPId := pId ; self.FName := name ; end;
procedure TForm1.N1Click(Sender: TObject); function getPNodeCount(): integer ;//得到根节点数 var i:integer ; cnt :integer ; begin cnt := 0 ; for i := 0 to tv1.Items.Count -1 do begin if (tv1.Items.Item[i].Level = 0 ) then begin cnt := cnt + 1 ; end; end;
Result := cnt ; end; var Node :TTreeNode ; id , pId :integer ; info ,addInfo :TAInfo ;
begin if tv1.Selected <> nil then //有选中节点 begin info := TAInfo(tv1.Selected.Data) ; addInfo := TAInfo.Create ; addInfo.ID := tv1.Selected.Count+1 ; addInfo.PId := info.ID ;//增加的节点的PID应该为选中的节点ID addInfo.Name := tv1.Selected.Text + '_' + IntToStr(addInfo.ID) ; Node := tv1.Items.AddChild(tv1.Selected, addInfo.Name) ; //1 Node.Data := addInfo ; //2 // 1和2 可以用下面语句代替 // Node := tv1.Items.AddChildObject(tv1.Selected, addInfo.Name, addInfo) ; end //没有选中节点,则增加根目录 else begin //因为没有实际数据,所以写了一个getPNodeCount id := getPNodeCount() ; addInfo := TAInfo.Create(id, 0 , '新增_' + IntToStr(id)); Node := tv1.Items.Add(nil, addInfo.Name) ; //1 Node.Data := addInfo ; //2 // 1和2 可以用下面语句代替 // Node := tv1.Items.AddObject(nil, addInfo.Name, addInfo) ; end;
end;
procedure TForm1.tv1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var s_dir: string; node: TTreeNode; begin if Button = mbRight then begin
tv1.Selected := tv1.GetNodeAt(X, Y); //确保在需要添加子节点的节点上面右键
end; end ;
end.
[code]
|