Difference between revisions of "TTreeView"

From Free Pascal wiki
Jump to navigationJump to search
Line 1: Line 1:
 
{{TTreeView}}
 
{{TTreeView}}
  
== About ==
+
A '''TTreeView''' is a graphical control element that presents a hierarchical view of information. Each item can have a number of subitems.
 
 
A [[doc:/lcl/comctrls/ttreeview.html| TTreeView ]] is a graphical control element that presents a hierarchical view of information. Each item can have a number of subitems.
 
  
 
An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems.
 
An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems.
  
 
==Adding a new item in code==
 
==Adding a new item in code==
 
 
Use TTreeView.Items.AddChild or AddChildObject.
 
Use TTreeView.Items.AddChild or AddChildObject.
 
  
 
==Creating a TreeView which loads items only when expansing==
 
==Creating a TreeView which loads items only when expansing==
 
 
To add the expansion symbol to a node without subitems use:
 
To add the expansion symbol to a node without subitems use:
  
Line 19: Line 14:
  
 
And then set an event handler for the OnExpanding event. In this even you should return if the expansion can actually be made or not and when yes, you should add subitems to the node. If the expansion cannot be done, the expansion symbol will be automatically removed even if you have previously set HasChildren to true.
 
And then set an event handler for the OnExpanding event. In this even you should return if the expansion can actually be made or not and when yes, you should add subitems to the node. If the expansion cannot be done, the expansion symbol will be automatically removed even if you have previously set HasChildren to true.
 
  
 
==A Short example of using TTreeview==
 
==A Short example of using TTreeview==
 
 
Here is a quick & dirty example - I tested on Windows Lazarus 0.9.26:
 
Here is a quick & dirty example - I tested on Windows Lazarus 0.9.26:
  
Line 30: Line 23:
  
 
Code:
 
Code:
 
+
<syntaxhighlight>
<syntaxhighlight>procedure TForm1.Button1Click(Sender: TObject);
+
procedure TForm1.Button1Click(Sender: TObject);
 
var  
 
var  
 
   i: integer;
 
   i: integer;
 
   s: string;
 
   s: string;
 
begin
 
begin
   // if there is no nodes, create a root node with a parent of Nil
+
   // if there are no nodes, create a root node with a parent of nil
 
   if TreeView1.Items.Count = 0 then
 
   if TreeView1.Items.Count = 0 then
    begin
+
  begin
      Treeview1.Items.Add (nil,'Root Node');
+
    Treeview1.Items.Add (nil,'Root Node');
      exit;
+
    exit;
    end;
+
  end;
 
   
 
   
 
   // Set up a simple text for each new node - Node1 , Node2 etc
 
   // Set up a simple text for each new node - Node1 , Node2 etc
Line 52: Line 45:
 
   
 
   
 
procedure TForm1.Button2Click(Sender: TObject);
 
procedure TForm1.Button2Click(Sender: TObject);
+
 
  //A procedure to recursively delete nodes
+
    //A procedure to recursively delete nodes
   Procedure DeleteNode(Node:TTreeNode);
+
   procedure DeleteNode(Node:TTreeNode);
 
   begin
 
   begin
     while Node.HasChildren do DeleteNode(node.GetLastChild);
+
     while Node.HasChildren do  
 +
      DeleteNode(node.GetLastChild);
 
     TreeView1.Items.Delete(Node) ;
 
     TreeView1.Items.Delete(Node) ;
 
   end;
 
   end;
 
   
 
   
 
begin
 
begin
   if TreeView1.Selected = nil then exit;
+
   if TreeView1.Selected = nil then  
   //If selected node has child nodes, first ask for confirmation
+
    exit;
   If treeview1.Selected.HasChildren then
+
    
     if messagedlg('Delete node and all children ?',mtConfirmation,
+
    //if selected node has child nodes, first ask for confirmation
                [mbYes,mbNo],0) <> mrYes then exit;
+
   if treeview1.Selected.HasChildren then
 +
     if messagedlg( 'Delete node and all children ?',mtConfirmation, [mbYes,mbNo],0 ) <> mrYes then  
 +
      exit;
 
   DeleteNode(TreeView1.Selected);
 
   DeleteNode(TreeView1.Selected);
end;</syntaxhighlight>
+
end;
 +
</syntaxhighlight>
  
 
When running, the treeview is empty.  If you click "Add Child", a root node is created.  After that a child will be added to any selected node by clicking "Add Child"
 
When running, the treeview is empty.  If you click "Add Child", a root node is created.  After that a child will be added to any selected node by clicking "Add Child"
Line 74: Line 71:
  
 
==Example of using Multiple Node Selection for Multiple User Selections==
 
==Example of using Multiple Node Selection for Multiple User Selections==
 
 
If you select your TTreeview component, go to the object inspector and in the options sections set 'tvoAllowMultiSelect' to true. Then, to iterate over the selected nodes and obtain the paths of the chosen folders or files, the following example will populate the text paths of those selected nodes to a memo field :  
 
If you select your TTreeview component, go to the object inspector and in the options sections set 'tvoAllowMultiSelect' to true. Then, to iterate over the selected nodes and obtain the paths of the chosen folders or files, the following example will populate the text paths of those selected nodes to a memo field :  
  
Line 93: Line 89:
  
 
== Freeing TreeNode Data ==
 
== Freeing TreeNode Data ==
 
 
Use the TreeView's OnDeletion event to free your object.
 
Use the TreeView's OnDeletion event to free your object.
  
Line 102: Line 97:
 
end;
 
end;
 
</syntaxhighlight>
 
</syntaxhighlight>
 
  
 
== Using Drag and Drop in a TreeView ==
 
== Using Drag and Drop in a TreeView ==
Line 114: Line 108:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
==See also ==
 +
* [[doc:/lcl/comctrls/ttreeview.html| TTreeView doc]]
 +
* [[TListView]]
  
{{LCL Components Footer|TProgressBar|TListView}}
 
 
{{LCL Components}}
 
{{LCL Components}}
 
 
[[Category:LCL]]
 
[[Category:Components]]
 

Revision as of 23:41, 21 July 2016

English (en) español (es) suomi (fi) français (fr) magyar (hu) русский (ru)

A TTreeView is a graphical control element that presents a hierarchical view of information. Each item can have a number of subitems.

An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems.

Adding a new item in code

Use TTreeView.Items.AddChild or AddChildObject.

Creating a TreeView which loads items only when expansing

To add the expansion symbol to a node without subitems use:

MyNode.HasChildren := True;

And then set an event handler for the OnExpanding event. In this even you should return if the expansion can actually be made or not and when yes, you should add subitems to the node. If the expansion cannot be done, the expansion symbol will be automatically removed even if you have previously set HasChildren to true.

A Short example of using TTreeview

Here is a quick & dirty example - I tested on Windows Lazarus 0.9.26:

Create a new application. On Form1 add an empty treeview, a button1 with caption "Add Child" and a button2 with caption "Delete"

For the buttons' OnClick events, assign the following code, compile & run.

Code:

procedure TForm1.Button1Click(Sender: TObject);
var 
  i: integer;
  s: string;
begin
  // if there are no nodes, create a root node with a parent of nil
  if TreeView1.Items.Count = 0 then
  begin
    Treeview1.Items.Add (nil,'Root Node');
    exit;
  end;
 
  // Set up a simple text for each new node - Node1 , Node2 etc
  i := treeview1.Items.Count;
  s := 'Node ' + inttostr(i);
  //Add a new node to the currently selected node
  if TreeView1.Selected <> nil then
    Treeview1.Items.AddChild(Treeview1.Selected ,s);
end;
 
procedure TForm1.Button2Click(Sender: TObject);

    //A procedure to recursively delete nodes
  procedure DeleteNode(Node:TTreeNode);
  begin
    while Node.HasChildren do 
      DeleteNode(node.GetLastChild);
    TreeView1.Items.Delete(Node) ;
  end;
 
begin
  if TreeView1.Selected = nil then 
    exit;
  
    //if selected node has child nodes, first ask for confirmation
  if treeview1.Selected.HasChildren then
    if messagedlg( 'Delete node and all children ?',mtConfirmation, [mbYes,mbNo],0 ) <> mrYes then 
      exit;
  DeleteNode(TreeView1.Selected);
end;

When running, the treeview is empty. If you click "Add Child", a root node is created. After that a child will be added to any selected node by clicking "Add Child"

Delete will delete the currently selected node. If it doesn't have children, it will delete it immediately, but if it has children, it will first ask.

Example of using Multiple Node Selection for Multiple User Selections

If you select your TTreeview component, go to the object inspector and in the options sections set 'tvoAllowMultiSelect' to true. Then, to iterate over the selected nodes and obtain the paths of the chosen folders or files, the following example will populate the text paths of those selected nodes to a memo field :

Code:

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
begin
  if TreeView1.SelectionCount=0 then
  exit;
  Memo1.Lines.Clear;
  for i:=0 to TreeView1.SelectionCount-1 do
  Memo1.Lines.Add(TreeView1.Selections[i].GetTextPath);
end;

Freeing TreeNode Data

Use the TreeView's OnDeletion event to free your object.

procedure TForm1.TreeView1Deletion(Sender: TObject; Node: TTreeNode);
begin
  TMyObject(Node.Data).Free;
end;

Using Drag and Drop in a TreeView

If you want to allow a drag and drop function in your treeview, you need to :

  1. Set to DmAutomatic, the property "Drag Mode" of your treeview
  2. Create an event for "OndragOver":
procedure TForm1.TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;  State: TDragState; var Accept: Boolean);
begin
  Accept := true;
end;

See also


LCL Components
Component Tab Components
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TTaskDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TCSVDataSet • TSdfDataSet • TBufDataset • TFixedFormatDataSet • TDbf • TMemDataset
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TJSONPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TLvlGraphControl • TShortPathEdit • TSpinEditEx • TFloatSpinEditEx • TTreeFilterEdit • TExtendedTabControl •
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TMySQL57Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHtmlDataProvider • TIpHttpDataProvider • TIpHtmlPanel
Virtual Controls TVirtualDrawTree • TVirtualStringTree • TVTHeaderPopupMenu