TTreeView/fr

From Free Pascal wiki
Jump to navigationJump to search

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

Un TTreeView ttreeview.png est un contrôle graphique qui présente une vue hiérarchique d'information. Chaque élément (Item) peut avoir des sous-éléments (arborescence).

Un élément peut être expansé pour révéler ses sous-éléments, s'il y en a, et contracté pour cacher les sous-éléments.

Le composant TTreeView est disponible depuis l'onglet Common Controls de la palette de composants

Ajout d'un nouvel élément par code

Utilisez TTreeView.Items.AddChild ou AddChildObject.

Création d'un TreeView qui charge des éléments seulement lors de l'expansion

Pour ajouter le symbole d'expansion à un nœud sans sous-éléments, utilisez :

MyNode.HasChildren := True;

Puis définissez un gestionnaire pour l'événement OnExpanding. Dans celui-ci, vous devriez retourner si l'expansion peut alors se faire ou non et dans l'affirmative vous devriez ajouter les sous-éléments au nœud. Si l'expansion ne peut pas se faire, le symbole d'expansion sera alors retiré automatiquement même si vous avez défini avant HasChildren à True.

Un court exemple d'utilisation de TTreeview

Voici un exemple vite fait - testé sur Lazarus 0.9.26 sur Windows :

Créez une nouvelle application. Sur le Form1 ajoutez un TreeView vide, un button1 intitulé "Add Child" et un button2 intitulé "Delete".

Pour l'événement OnClick des boutons, affectez le code suivant, compilez et exécutez.

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( 'Supprimer le noeud et tous ses enfants ?',mtConfirmation, [mbYes,mbNo],0 ) <> mrYes then 
      exit;
  DeleteNode(TreeView1.Selected);
end;

A l'exécution, le TreeView est vide. Si vous cliquez sur "Add Child", un nœud racine est créé. Après un élément enfant sera ajouté au noeud sélectionné en cliquant sur "Add Child".

"Delete" supprimera le nœud actuellement sélectionné. Si il n'a pas d'enfant, il sera supprimé immédiatement mais s'il en a, il va d'abord demander.

Exemple d'utilisation de sélection multiple de nœud pour les sélections multiples de l'utilisateur

Si vous sélectionnez votre composant TTreeview, allez dans l'objet d'objet et dans les sections d'options mettez tvoAllowMultiSelect à True. Ensuite, pour itérer sur les nœuds sélectionnés et obtenir les chemins des dossiers choisis ou des fichiers, l'exemple suivant peuplera les chemins à ces nœuds sélectionnés en texte dans un champ mémo :

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;

Libération des données de TreeNode

Utilisez l'événement OnDeletion du TreeView pour libérer votre objet.

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

Utilisation du Glisser/déposer (Drag and Drop) dans un TreeView

Si vous voulez permettre des fonctions de Glisser/déposer dans votre TreeView, vous avez besoin de :

  1. Définir à DmAutomatic, la propriété DragMode de votre TreeView.
  2. Créer un événement pour OndragOver.
procedure TForm1.TreeView1DragOver(Sender, Source: TObject; X, Y: Integer;  State: TDragState; var Accept: Boolean);
begin
  Accept := true;
end;

Voir aussi


Composant LCL
Onglet de palette Composants
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 • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog • TTaskDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TBufDataset • TMemDataset • TSdfDataSet • TFixedFormatDataSet • TDbf
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 • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TTreeFilterEdit • TShortPathEdit • TLvlGraphControl
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 • 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 • TIpHttpDataProvider • TIpHtmlPanel