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 := 'Nodo ' + 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 }
  // Si el nodo seleccionado tiene nodos hijo, primero preguntar por confirmación
  If treeview1.Selected.HasChildren then
    if messagedlg('¿Borrar nodo y todos los nodos hijo?',mtConfirmation,
                 [mbYes,mbNo],0) <> mrYes then exit; { Muestra mensaje de confirmación de borrado (pulsadores Si/No), caso de que }
                                                     { la contestación sea diferente de Si, entonces sale del if sin borrar nodo }
  DeleteNode(TreeView1.Selected); { Borra el nodo actualmente seleccionado }
end;

Cuando se ejecuta, el treeview está vacío,. Si se hace click en "Añadir hijo", se crea un nodo raíz. Después de esto se crea un nodo hijo en el nodo que tengamos seleccionado haciendo click en el pulsador "Añadir hijo".

El pulsador Borrar lo que hace es borrar el nodo actualmente seleccionado. Si no tiene nodos hijo lo borrara inmediatamente, pero si los tiene preguntará primero para confirmar su borrado.