TTreeView/es

From Lazarus wiki
Jump to navigationJump to search

Añadir un nuevo elemento mediante código

Se puede añadir un nuevo elemento mediante TTreeView.Items.AddChild o bien AddChildObject.

Crear un TreeView que carga elementos solamente cuando se expande

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.

Un pequeño ejemplo de uso de TTreeview

Here is a quick & dirty example - testeado en Lazarus 0.9.26 bajo Windows:

Crear una nueva aplicación. En Form1 añadir un treeview vacío, un button1 con caption "Añadir hijo" y un button2 con caption "Borrar"

Para los buttons' con su evento OnClick, asignar el siguiente código, compilar y ejecutar.

Codigo:

procedure TForm1.Button1Click(Sender: TObject);
var 
  i: integer;
  s: string;
begin
  // si no hay nodos, crear un nodo raíz con un padre establecido al valor Nil
  if TreeView1.Items.Count = 0 then
    begin
      Treeview1.Items.Add (nil,'Nodo Raíz');
      exit;
    end;
 
  // Establer un texto simple para cada nuevo nodo: Nodo1 , Nodo2, etc
  i := treeview1.Items.Count; { nos retorna la cuenta total de elementos }
  s := 'Node ' + inttostr(i); { crea la cadena de texto 'Node ' más el número resultante de conversión de entero su equivalente en texto }
  // Añade un nuevo nodo al nodo actualmente seleccionado.
  if TreeView1.Selected <> nil then { Si tenemos seleccionado un nodo entonces hacer lo siguiente }
    Treeview1.Items.AddChild(Treeview1.Selected ,s); { Añadir un elemento como hijo al actualmente seleccionado }
end;
 
procedure TForm1.Button2Click(Sender: TObject);
 
  // Un procedimiento para borrar nodos recursivmente
  Procedure DeleteNode(Node:TTreeNode);
  begin
    while Node.HasChildren do DeleteNode(node.GetLastChild); { mientras el nodo tenga hijos realizar borrado último nodo hijo }
    TreeView1.Items.Delete(Node) ; { borra nodo que ya no contiene nodos hijo } 
  end;
 
begin
  if TreeView1.Selected = nil then exit; { salir del borrado caso de que no tengamos seleccionado un nodo }
  //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.