Difference between revisions of "VirtualTreeview Example for Lazarus/fr"

From Free Pascal wiki
Jump to navigationJump to search
m (Add syntax coloration.)
 
(9 intermediate revisions by 2 users not shown)
Line 5: Line 5:
 
=Arbre de base Listview avec trois Colonnes=
 
=Arbre de base Listview avec trois Colonnes=
  
1. Installez le composant. Exécutez lazarus.
+
1. Installez le composant. Exécutez lazarus.
  
 
2. Déposez un composant TVirtualStringTree (Sous l'onglet Virtual Controls).
 
2. Déposez un composant TVirtualStringTree (Sous l'onglet Virtual Controls).
  
 
3. Aller à l'éditeur de source (Appuyez sur F12). Sous la clause Uses ajoutez une unité - appelée VirtualTrees (si elle n'est pas déjà là et que ce n'est pas VirtualStringTree). Ainsi, il peut ressembler à:
 
3. Aller à l'éditeur de source (Appuyez sur F12). Sous la clause Uses ajoutez une unité - appelée VirtualTrees (si elle n'est pas déjà là et que ce n'est pas VirtualStringTree). Ainsi, il peut ressembler à:
<PRE>
+
<syntaxhighlight lang=pascal>
 
uses
 
uses
 
   Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
 
   Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
 
   VirtualStringTree, VirtualTrees;  
 
   VirtualStringTree, VirtualTrees;  
</PRE>   
+
</syntaxhighlight>   
 
4. Aller à l'éditeur de fiches (Appuyez sur  F12). Sélectionnez le composant Virtual Tree. Sur l'inspecteur d'objet cliquez sur Name, tapez VST et appuyez sur entrer. Cliquez sur Header (augmentez-le) -> Columns, cliquez sur le petit bouton situé à côté de "0 items". Cliquez 3 fois sur Add button pour ajouter 3 colonnes. Ne pas fermer cette fenêtre.
 
4. Aller à l'éditeur de fiches (Appuyez sur  F12). Sélectionnez le composant Virtual Tree. Sur l'inspecteur d'objet cliquez sur Name, tapez VST et appuyez sur entrer. Cliquez sur Header (augmentez-le) -> Columns, cliquez sur le petit bouton situé à côté de "0 items". Cliquez 3 fois sur Add button pour ajouter 3 colonnes. Ne pas fermer cette fenêtre.
  
Line 30: Line 30:
  
 
[[Image:ExempleVirtualtreeView1.jpg|center]]
 
[[Image:ExempleVirtualtreeView1.jpg|center]]
 
  
 
11. Faites défiler la liste jusqu'à TreeOptions(augmentez-le) -> MiscOption(augmentez-le), fixez toEditable à True. Fixez toGridExtensions à True.
 
11. Faites défiler la liste jusqu'à TreeOptions(augmentez-le) -> MiscOption(augmentez-le), fixez toEditable à True. Fixez toGridExtensions à True.
Line 39: Line 38:
  
 
14. CLiquez sur Button1, sur l'inspecteur d'object changez Caption avec AddRoot. Cliquez sur Button2, changez le caption avec AddChild. Changez le caption du Button3 avec Delete.
 
14. CLiquez sur Button1, sur l'inspecteur d'object changez Caption avec AddRoot. Cliquez sur Button2, changez le caption avec AddChild. Changez le caption du Button3 avec Delete.
 +
 +
[[Image:ExempleVirtualtreeView2.jpg|center]]
  
 
15. Gardez ceci ici et allez à l'éditeur de source(appuyez sur F12). Dans l'éditeur de source remplacez la ligne:
 
15. Gardez ceci ici et allez à l'éditeur de source(appuyez sur F12). Dans l'éditeur de source remplacez la ligne:
Line 46: Line 47:
 
16. Sous "implementation" coller les lignes suivantes:
 
16. Sous "implementation" coller les lignes suivantes:
  
<PRE>
+
<syntaxhighlight lang=pascal>
 
type
 
type
 
   PTreeData = ^TTreeData;
 
   PTreeData = ^TTreeData;
Line 54: Line 55:
 
     Column2: String;
 
     Column2: String;
 
   end;
 
   end;
</PRE>
+
</syntaxhighlight>
  
17. Get to the Form Designer (press F12). Select VST. Go to Object Inspector, select Events tab, scroll down to onChange. Double click on the combobox. Paste the follwings:
+
17. Allez au concepteur de fiche (Appuyez sur F12). sélectionnez VST. Allez à l'inspecteur d'objet, sélectionnez l'onglet évènements, défiler vers le bas vers l'évènement onChange. Double-cliquez sur le combobox. Coller ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
procedure TForm1.VSTChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
begin
 
begin
 
  VST.Refresh;
 
  VST.Refresh;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
18. Scroll to onFocusChanged. Double click and paste the follwings:
+
18. Faites défiler jusqu'à onFocusChanged. Double-cliquez et collez ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Column: TColumnIndex);
 
   Column: TColumnIndex);
Line 71: Line 72:
 
   VST.Refresh;
 
   VST.Refresh;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
 
    
 
    
19. Scroll to onFreeNode. Double click and paste the follwings:
+
19. Faites défiler jusqu'à onFreeNode. Double-cliquez et collez ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
procedure TForm1.VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
var
 
var
Line 86: Line 87:
 
  end;
 
  end;
 
end;   
 
end;   
</PRE>
+
</syntaxhighlight>
  
20. Scroll down to onGetNodeDataSize. Double click & paste the follwings:  
+
20. Faites défiler jusqu'à onGetNodeDataSize. Double-cliquez et collez ce qui suit:  
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
 
procedure TForm1.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
 
begin
 
begin
 
     NodeDataSize := SizeOf(TTreeData);
 
     NodeDataSize := SizeOf(TTreeData);
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
21. Scroll to onGetText. Double click & paste the follwings:  
+
21. Faites défiler jusqu'à onGetText. Double-cliquez et collez ce qui suit:  
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
  Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
 
  Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
Line 110: Line 111:
 
   end;
 
   end;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
22. Press F12 to get Form Designer. Double click AddRoot button. Paste the followings:
+
22. Pressez sur F12 pour aller à concepteur de fiche. Double-cliquez sur le bouton AddRoot. Collez ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button1Click(Sender: TObject);
 
procedure TForm1.Button1Click(Sender: TObject);
 
Var
 
Var
Line 132: Line 133:
 
   End;  
 
   End;  
 
End;  
 
End;  
</PRE>
+
</syntaxhighlight>
  
23. Press F9 to Run the project to check. Click on AddRoot to add node. If it is ok, node will be added on VST.
+
23. Appuyez sur F9 pour exécuter le projet à vérifier. Cliquez sur AddRoot pour ajouter un nœud. Si c'est ok, le nœud sera ajouté sur VST.
  
24. Stop execution. On the Form Designer double click the AddChild captioned button. Paste the followings:
+
[[Image:ExempleVirtualtreeView3.jpg|center]]
<PRE>
+
 
 +
24. Arrêtez l'exécution. Sur le concepteur de fiche double-cliquez sur le bouton intitulé addChild. Collez ce qui suit:
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button2Click(Sender: TObject);
 
procedure TForm1.Button2Click(Sender: TObject);
 
var
 
var
Line 155: Line 158:
 
   VST.Expanded[VST.FocusedNode]:=True;
 
   VST.Expanded[VST.FocusedNode]:=True;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
25. On the Form Designer double click the Delete captioned button. Paste the followings:
+
25. Sur le concepteur de fiche double-cliquez sur le bouton intitulé Delete. Copiez ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button3Click(Sender: TObject);
 
procedure TForm1.Button3Click(Sender: TObject);
 
begin
 
begin
 
   VST.DeleteSelectedNodes;
 
   VST.DeleteSelectedNodes;
 
end;   
 
end;   
</PRE>
+
</syntaxhighlight>
  
26. Run the project by pressing F9 to check. Add some node, child and delete them.
+
26. Exécutez le projet en appuyant sur la touche F9 pour vérifier. Ajoutez quelques nœuds, nœuds fils et effacez les.
  
27. Try to edit a node. Select a node and press F2, write new value. If you can see what you are typing then it is OK. Else, read bellow "If Cell Editing Can't Be Seen".
+
[[Image:ExempleVirtualtreeView4.jpg|center]]
  
28. To get VST show the new value entered after editing, go to the Form Designer, select VST. On Object Inspector -> Events -> OnNewText combobox double click. Paste the followings:
+
27. Essayez d'éditer un nœud. Sélectionnez un nœud et pressez sur F2, écrivez une nouvelle valeur. Si vous pouvez voir ce que vous tapez alors c'est OK. Sinon, lisez-dessous "Si l'édition d'une cellule ne peut être vue".
<PRE>
+
 
 +
28. Pour obtenir que VST montre la nouvelle valeur après l'édition, allez au concepteur de fiche, sélectionnez VST. Double-cliquez sur le combobox de l'inspecteur d'objet -> Evenements -> OnNewText. Copiez ce qui suit:
 +
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Column: TColumnIndex; NewText: WideString);
 
   Column: TColumnIndex; NewText: WideString);
Line 183: Line 188:
 
  End;
 
  End;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
So far, example for basic use ends here. You may drop few more buttons on the form to test few more commands given bellow. Next would be, showing checkbox, image, font colour and adding combobox on node.  
+
Jusqu'à présent, l'exemple de l'utilisation de base se termine ici. Vous pouvez mettre quelques boutons de plus sur la fiche afin de tester quelques commandes indiquées ci-dessous. La suite serait de montrer les cases à cocher, les images, la couleur des caractères et l'ajout de combobox sur un noeud.  
  
  
*Another Way To Add Root Node
+
*Une autre manière d'ajouter le nœud racine
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button8Click(Sender: TObject);
 
procedure TForm1.Button8Click(Sender: TObject);
 
begin
 
begin
Line 195: Line 200:
 
   RootNodeCount:=RootNodeCount+1;
 
   RootNodeCount:=RootNodeCount+1;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Another Way To Add Child
+
*Une autre façon d'ajouter un nœud enfant
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button9Click(Sender: TObject);
 
procedure TForm1.Button9Click(Sender: TObject);
 
begin
 
begin
Line 203: Line 208:
 
   VST.ChildCount[VST.FocusedNode]:=VST.ChildCount[VST.FocusedNode]+1;
 
   VST.ChildCount[VST.FocusedNode]:=VST.ChildCount[VST.FocusedNode]+1;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Determine & Delete Children Of A Node
+
*Déterminer et effacer un enfant d'un nœud donné
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button4Click(Sender: TObject);
 
procedure TForm1.Button4Click(Sender: TObject);
 
Var
 
Var
Line 219: Line 224:
 
   End;
 
   End;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
*Delete Node
+
*Effacer un nœud
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button5Click(Sender: TObject);
 
procedure TForm1.Button5Click(Sender: TObject);
 
begin
 
begin
Line 229: Line 234:
 
   VST.DeleteNode(VST.FocusedNode);
 
   VST.DeleteNode(VST.FocusedNode);
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Search And Select Node
+
*Rechercher et sélectionner un nœud
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button6Click(Sender: TObject);
 
procedure TForm1.Button6Click(Sender: TObject);
 
Var
 
Var
Line 253: Line 258:
 
  End;
 
  End;
 
End;
 
End;
</PRE>
+
</syntaxhighlight>
 
*Determine Parent
 
*Determine Parent
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button13Click(Sender: TObject);
 
procedure TForm1.Button13Click(Sender: TObject);
 
var
 
var
Line 271: Line 276:
 
   VST.SetFocus;
 
   VST.SetFocus;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
*Search All
+
*Tout rechercher
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button7Click(Sender: TObject);
 
procedure TForm1.Button7Click(Sender: TObject);
 
Var
 
Var
Line 291: Line 296:
 
   Until XNode = VST.GetLast();
 
   Until XNode = VST.GetLast();
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Insert Node
+
*Insérer un nœud
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button12Click(Sender: TObject);
 
procedure TForm1.Button12Click(Sender: TObject);
 
var
 
var
Line 306: Line 311:
 
   end;
 
   end;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Set Node Height
+
*Fixer la hauteur d'un nœud
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button14Click(Sender: TObject);
 
procedure TForm1.Button14Click(Sender: TObject);
 
begin
 
begin
Line 314: Line 319:
 
   VST.NodeHeight[VST.FocusedNode] := 32;
 
   VST.NodeHeight[VST.FocusedNode] := 32;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Save And Load
+
*Sauvegarde et chargement
Simple tree (without column) can be saved and loaded as:
+
Un arbre simple (sans colonne) peut être sauvegardé et chargé ainsi:
<PRE>
+
<syntaxhighlight lang=pascal>
 
VST.SaveToFile('filename.dat');
 
VST.SaveToFile('filename.dat');
 
VST.LoadFromFile('filename.dat');
 
VST.LoadFromFile('filename.dat');
</PRE>
+
</syntaxhighlight>
 
<br>
 
<br>
To save and load the above mentioned example, place 2 buttons on the form, rename caption to "Save" and "Load". Select VST, on Object Inspector -> TreeOptions -> StringOptions make sure toSaveCaptions is set to True. Go to Object Inspector's Events tab. Scroll down to OnLoadNode, double click and then paste:
+
Pour enregistrer et charger l'exemple mentionné ci-dessus, placez 2 boutons sur la fiche, renommez le caption avec "Save" pour le 1er et "Load" pour le second. Sélectionnez VST, sur l'inspecteur d'objet -> TreeOptions -> StringOptions assurez-vous que toSaveCaptions est fixé à True. Allez à l'onglet évènements de l'inspecteur d'objet. Faites défiler la liste jusqu'à OnLoadNode, double-cliquez, puis collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTLoadNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTLoadNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Stream: TStream);
 
   Stream: TStream);
Line 343: Line 348:
 
  Stream.read(PChar(Data^.Column2)^, Len);
 
  Stream.read(PChar(Data^.Column2)^, Len);
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
Again on Object Inspector's Events tab - scroll down to OnSaveNode, double click and then paste:
+
A nouveau sur l'onglet évènements de l'inspecteur d'objet - défiler vers le bas vers OnSaveNode, double-cliquez, puis collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTSaveNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTSaveNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Stream: TStream);
 
   Stream: TStream);
Line 366: Line 371:
 
  Stream.write(PChar(Data^.Column2)^, Len);
 
  Stream.write(PChar(Data^.Column2)^, Len);
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
On Form Designer double click Save captioned button, paste:
+
Sur le concepteur de fiche double-cliquez sur le bouton intitulé Save, collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button10Click(Sender: TObject);
 
procedure TForm1.Button10Click(Sender: TObject);
 
begin
 
begin
 
  VST.SaveToFile('C:\vst.dat');
 
  VST.SaveToFile('C:\vst.dat');
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
On Form Designer double click Load captioned button, paste:
+
Sur le concepteur de fiche double-cliquez sur le bouton intitulé Load, collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Button11Click(Sender: TObject);
 
procedure TForm1.Button11Click(Sender: TObject);
 
begin
 
begin
 
   VST.LoadFromFile('C:\vst.dat');
 
   VST.LoadFromFile('C:\vst.dat');
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
Now test to save and load tree.
+
Testez maintenant l'enregistrement et le chargement de l'arbre.
  
*Scroll Problem
+
*Problème de défilement
The header of the treeview disappears fully or partially when scrolling. I could not find a good solution for this. One way to overcome this is to set the header height to 0, then using general label for columns. This is good while there are few columns, and all are visible without horizontal scrolling. Or, the header height can be set to a higher value like 25 or 30. VST.Refresh can be added to the OnScroll event.
+
L'en-tête du treeview disparaît totalement ou partiellement lors du défilement. Je n'ai pas pu trouver une bonne solution pour cela. Une façon de surmonter ceci est de fixer la hauteur de l'en-tête à 0, puis d'utiliser un label général pour les colonnes. C'est bon tant qu'il y a peu de colonnes, et quelles sont toutes visibles sans défilement horizontal. Ou bien, la hauteur de l'en-tête peut être réglée à une valeur plus élevée de 25 ou 30. VST.Refresh peut être ajouté à l'évènement OnScroll.
  
*Column Resize
+
*Redimensionnement des colonnes
It was not possible to resize column by dragging mouse on VST header. May be it is for the header bug or I have missed something. If it is for the header, probably will be fixed on next version of Lazarus. See this link: http://bugs.freepascal.org/view.php?id=11209<br>
+
Il n'est pas possible de redimensionner une colonne en faisant glisser la souris sur l'en-tête de VST. Peut être c'est à cause d'un bug de l'en-tête ou j'ai oublié quelque chose. Si c'est à cause de l'en-tête, ça sera probablement fixé avec la prochaine version de Lazarus. Voir ce lien: http://bugs.freepascal.org/view.php?id=11209<br>
Anyway, it is possible to resize column from code. When you press down right mouse button and move mouse-wheel up, the width of the selected column increases and press down the right mouse button and move mouse-wheel down, to decrease the width of the selected column. To do this:<br>
+
Quoi qu'il en soit, il est possible de redimensionner la colonne à partir du code. Lorsque vous appuyez sur le bouton droit de la souris et déplacez la roulette vers le haut, la largeur de la colonne sélectionnée augmente et appuyez sur le bouton droit de la souris et déplacez la roulette vers le bas, pour diminuer la largeur de la colonne sélectionnée. Pour faire ceci:<br>
  
1. Add a variable in the source editor named as CurCol: Integer; So it looks like:
+
1. Ajouter une variable dans l'éditeur de source nommé CurCol: Integer; Ainsi, le code ressemble à:
<PRE>
+
<syntaxhighlight lang=pascal>
 
var
 
var
 
   Form1: TForm1;  
 
   Form1: TForm1;  
Line 401: Line 406:
  
 
{ TForm1 }  
 
{ TForm1 }  
</PRE>
+
</syntaxhighlight>
  
2. On the Form Designer double click the form to generate an event OnCreate. Inside the OnCreate procedure type Form1.OnMouseWheelUp:= and press Ctrl+Shift+C, this will complete the code and make skeleton of the MouseWheelUp event. Now get back to procedure TForm1.FormCreate(Sender: TObject); And add another event for MouseWheelDown. Type Form1.OnMouseWheelDown:= and press Ctrl+Shift+C, to generate the MouseWheelDown event. FormCreate procedure now looks like:
+
2. Sur le concepteur de fiche double-cliquez sur le fiche pour générer l'évènement OnCreate. Dans la procédure OnCreate tapez Form1.OnMouseWheelUp:= et appuyez sur Ctrl+Shift+C, ceci va compléter le code et faire le squelette de l'évènement MouseWheelUp. Maintenant revenir à la procédure TForm1.FormCreate(Sender: TObject); et ajoutez un nouvel évènement pour MouseWheelDown. Tapez Form1.OnMouseWheelDown:= et appuyez sur Ctrl+Shift+C, pour générer l'évènement MouseWheelDown. La procédure FormCreate ressemble maintenant à :
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.FormCreate(Sender: TObject);
 
procedure TForm1.FormCreate(Sender: TObject);
 
begin
 
begin
Line 410: Line 415:
 
     Form1.OnMouseWheelDown:=@Form1MouseWheelDown;
 
     Form1.OnMouseWheelDown:=@Form1MouseWheelDown;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
3. Fill the TForm1.Form1MouseWheelUp procedure as:
+
3. Remplissez la procédure TForm1.Form1MouseWheelUp ainsi:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Form1MouseWheelUp(Sender: TObject; Shift: TShiftState;
 
procedure TForm1.Form1MouseWheelUp(Sender: TObject; Shift: TShiftState;
 
   MousePos: TPoint; var Handled: Boolean);
 
   MousePos: TPoint; var Handled: Boolean);
Line 421: Line 426:
 
  VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width + 10;
 
  VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width + 10;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
4. Fill the TForm1.Form1MouseWheelDown procedure as:
+
4. Remplissez la procédure TForm1.Form1MouseWheelDown ainsi:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.Form1MouseWheelDown(Sender: TObject; Shift: TShiftState;
 
procedure TForm1.Form1MouseWheelDown(Sender: TObject; Shift: TShiftState;
 
   MousePos: TPoint; var Handled: Boolean);
 
   MousePos: TPoint; var Handled: Boolean);
Line 432: Line 437:
 
  VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width - 10;
 
  VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width - 10;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
5. Go to the Form Designer (press F12), select VST, on Object Inspector's Events tab scroll to OnFocusChanged, double click & paste:
+
5. Allez au concepteur de fiche (appuyez sur F12), sélectionnez VST, sur l'onglet des évènement de l'inspecteur d'objet faites défiler jusqu'à OnFocusChanged, double-cliquez et collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree;
 
procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree;
 
   Node: PVirtualNode; Column: TColumnIndex);
 
   Node: PVirtualNode; Column: TColumnIndex);
Line 441: Line 446:
 
   CurCol:=Column;
 
   CurCol:=Column;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
When you run, click on a column then hold down right mouse button and move wheel up to increase width, wheel down to decrease. You may tune-up the above procedures if needed. Or, add keyboard event with something like "if (key=187) and (ssShift in Shift) then" to watch for Shift + "+".
+
Lorsque vous exécutez le programme, cliquez sur une colonne puis maintenez enfoncé le bouton droit de la souris et faire bouger la roulette vers le haut pour augmenter la largeur de la colonne, et le roulette vers le bas pour la diminuer. Vous devriez mettre au point les procédures ci-dessus si nécessaire. Ou bien, ajoutez un évènement au clavier avec quelque chose du genre "if (key=187) and (ssShift in Shift) then" pour surveiller le Shift + "+".
 
----
 
----
 
----
 
----
Line 449: Line 454:
 
=Checkbox=
 
=Checkbox=
 
----
 
----
On Form Designer select VST. Go to:<br>  
+
Sur le concepteur de fiche sélectionnez VST. Allez à:<br>  
#Object Inspector -> Properties -> CheckImageKind and select ckDarkCheck.
+
#Inspecteur d'objets -> Propriétés -> CheckImageKind et sélectionnez ckDarkCheck.
#Object Inspector -> Properties -> TreeOptions -> MiscOptions -> toCheckSupport and set it to True.<br>
+
#Inspecteur d'objets -> Propriétés -> TreeOptions -> MiscOptions -> toCheckSupport et la mettre à True.<br>
Now switch to Events tab.<br>
+
Maintenant passer à l'onglet évènements.<br>
*Scroll to OnInitNode. Double click and paste the followings:
+
*Faites défiler jusqu'à OnInitNode. Double-cliquez et collez ce qui suit:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTInitNode(Sender: TBaseVirtualTree; ParentNode,
 
procedure TForm1.VSTInitNode(Sender: TBaseVirtualTree; ParentNode,
 
   Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
 
   Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
Line 476: Line 481:
 
     Node.CheckType:=ctButton;
 
     Node.CheckType:=ctButton;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
Run the program, add rootnode and child then child of the child, and check if you can check and uncheck properly. If not, close the program. Go to the Object Inspector's Events tab.
+
Lancez le programme, ajoutez le nœud racine et un nœud enfant puis l'enfant d'un enfant, et vérifiez si vous pouvez cocher et décocher correctement. Si non, fermez le programme. Allez à l'onglet évènements de l'inspecteur d'objets.
*Scroll to OnChecked, double click and paste:
+
*Faites défiler jusqu'à OnChecked, double-cliquez et collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
begin
 
begin
 
   vst.Refresh;
 
   vst.Refresh;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
*Scroll to OnChecking, double click and paste:
+
*Faites défiler jusqu'à OnChecking, double-cliquez et collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTChecking(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTChecking(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   var NewState: TCheckState; var Allowed: Boolean);
 
   var NewState: TCheckState; var Allowed: Boolean);
Line 492: Line 497:
 
  VST.Refresh;
 
  VST.Refresh;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
Hope now it is ok. To determine checkbox state use like:<BR>
+
J'espère maintenant que c'est ok. Pour déterminer l'état du checkbox utilisez quelque chose comme:<BR>
  
 
If XNode.CheckState = csCheckedNormal then<br>
 
If XNode.CheckState = csCheckedNormal then<br>
 
ShowMessage('Checked.');<br>
 
ShowMessage('Checked.');<br>
  
Other states are:<br>
+
Les autres états sont:<br>
<PRE>
+
<syntaxhighlight lang=pascal>
 
csUncheckedNormal = unchecked and not pressed
 
csUncheckedNormal = unchecked and not pressed
 
csUncheckedPressed = unchecked and pressed
 
csUncheckedPressed = unchecked and pressed
Line 506: Line 511:
 
csMixedNormal = 3-state check box and not pressed
 
csMixedNormal = 3-state check box and not pressed
 
csMixedPressed = 3-state check box and pressed
 
csMixedPressed = 3-state check box and pressed
</PRE>
+
</syntaxhighlight>
  
Other types are:<br>
+
Les autres types sont:<br>
<PRE>
+
<syntaxhighlight lang=pascal>
 
ctNone
 
ctNone
 
ctTriStateCheckBox
 
ctTriStateCheckBox
Line 515: Line 520:
 
ctRadioButton
 
ctRadioButton
 
ctButton
 
ctButton
</PRE>
+
</syntaxhighlight>
*To Catch Checkbox's Button (ctButton) Click
+
*Pour capturer le clic du bouton Checkbox (ctButton)  
Go to Object Inspector's Events tab. Scroll to OnChecked, double click and paste:
+
Allez à l'onglet évènements de l'inspecteur d'objets. Faites défiler jusqu'à OnChecked, double-cliquez et collez:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
 
begin
 
begin
Line 525: Line 530:
 
  VST.Refresh;
 
  VST.Refresh;
 
end;   
 
end;   
</PRE>
+
</syntaxhighlight>
End of checkbox.<br>
+
Fin de checkbox.<br>
  
 
----
 
----
 
----
 
----
 +
 
=Image & Font Colour=
 
=Image & Font Colour=
 
----
 
----
Line 536: Line 542:
 
*Now on the Form Designer select VST, and on Object Inspector's Properties tab, scroll to Images and select ImageList1
 
*Now on the Form Designer select VST, and on Object Inspector's Properties tab, scroll to Images and select ImageList1
 
*On Object Inspector's Events tab scroll to OnGetImageIndex, double click and paste:
 
*On Object Inspector's Events tab scroll to OnGetImageIndex, double click and paste:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean;
 
   Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean;
Line 555: Line 561:
 
  {Sender.NodeHeight[node]:=40; //If Image is big}
 
  {Sender.NodeHeight[node]:=40; //If Image is big}
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
 
=====Font Colour=====
 
=====Font Colour=====
 
On the Form Designer select VST, and on Object Inspector's Events tab, scroll to OnPaintText, double click and paste:
 
On the Form Designer select VST, and on Object Inspector's Events tab, scroll to OnPaintText, double click and paste:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTPaintText(Sender: TBaseVirtualTree;
 
procedure TForm1.VSTPaintText(Sender: TBaseVirtualTree;
 
   const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
 
   const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
Line 583: Line 589:
 
  end;
 
  end;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
 
Image & Font Colour ends here.
 
Image & Font Colour ends here.
  
Line 590: Line 596:
  
 
*Bellow there is an unit file named combo. Copy that unit and save as combo.pas inside the project directory. Under your program's uses clause add combo. So it may look like:
 
*Bellow there is an unit file named combo. Copy that unit and save as combo.pas inside the project directory. Under your program's uses clause add combo. So it may look like:
<PRE>
+
<syntaxhighlight lang=pascal>
 
uses
 
uses
 
   Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
 
   Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
 
   VirtualStringTree, VirtualTrees, combo;
 
   VirtualStringTree, VirtualTrees, combo;
</PRE>
+
</syntaxhighlight>
  
 
*The combo.pas unit
 
*The combo.pas unit
<PRE>
+
<syntaxhighlight lang=pascal>
 
unit combo;
 
unit combo;
  
Line 731: Line 737:
  
 
End.
 
End.
</PRE>
+
</syntaxhighlight>
  
 
*After saving the file, on the Form Designer select VST and on Object Inspector's Properties, scroll to TreeOptions -> MiscOptions, set toEditable to True. Then get to TreeOptions -> SelectionOptions, set toExtendedFocus to True.
 
*After saving the file, on the Form Designer select VST and on Object Inspector's Properties, scroll to TreeOptions -> MiscOptions, set toEditable to True. Then get to TreeOptions -> SelectionOptions, set toExtendedFocus to True.
  
 
*Switch to Object Inspector's Events tab. Scroll to OnCreateEditor, double click and paste:
 
*Switch to Object Inspector's Events tab. Scroll to OnCreateEditor, double click and paste:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTCreateEditor(Sender: TBaseVirtualTree;
 
procedure TForm1.VSTCreateEditor(Sender: TBaseVirtualTree;
 
   Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink);
 
   Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink);
Line 742: Line 748:
 
   EditLink:=TStringEditLink.Create;
 
   EditLink:=TStringEditLink.Create;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
  
 
*On Object Inspector's Events tab. Scroll to OnNewText, double click and paste:
 
*On Object Inspector's Events tab. Scroll to OnNewText, double click and paste:
<PRE>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 
   Column: TColumnIndex; NewText: WideString);
 
   Column: TColumnIndex; NewText: WideString);
Line 758: Line 764:
 
End;
 
End;
 
end;
 
end;
</PRE>
+
</syntaxhighlight>
 
Run program, select a node and press F2 to get combobox. On pressing Enter new value should appear on the node.
 
Run program, select a node and press F2 to get combobox. On pressing Enter new value should appear on the node.
  
Line 766: Line 772:
 
under Uses clause and select Find Declaration. This opens the file on next tab. Go to that file's tab.). Get to the "function TStringEditLink.BeginEdit: Boolean; stdcall;".
 
under Uses clause and select Find Declaration. This opens the file on next tab. Go to that file's tab.). Get to the "function TStringEditLink.BeginEdit: Boolean; stdcall;".
 
It looks like:
 
It looks like:
<PRE>     
+
<syntaxhighlight lang=pascal>     
 
function TStringEditLink.BeginEdit: Boolean; stdcall;
 
function TStringEditLink.BeginEdit: Boolean; stdcall;
  
Line 781: Line 787:
 
   end;
 
   end;
 
end;  
 
end;  
</PRE>     
+
</syntaxhighlight>     
  
 
Now add "FEdit.Height:=18;". It should look like:
 
Now add "FEdit.Height:=18;". It should look like:
  
<PRE>
+
<syntaxhighlight lang=pascal>
 
function TStringEditLink.BeginEdit: Boolean; stdcall;
 
function TStringEditLink.BeginEdit: Boolean; stdcall;
  
Line 801: Line 807:
 
   end;
 
   end;
 
end;  
 
end;  
</PRE>
+
</syntaxhighlight>
  
 
Save the file (press Ctrl + S). If you are on the example project, close this (Project -> Close Project). Click on Tools -> Configure "Build Lazarus" ... Select Clean Up + Build All and then click on the Build button. After compile Lazarus should be restarted. Now open the example project and try to edit node on VST. This time it should be ok.
 
Save the file (press Ctrl + S). If you are on the example project, close this (Project -> Close Project). Click on Tools -> Configure "Build Lazarus" ... Select Clean Up + Build All and then click on the Build button. After compile Lazarus should be restarted. Now open the example project and try to edit node on VST. This time it should be ok.

Latest revision as of 18:09, 12 November 2020

English (en) español (es) français (fr) polski (pl) русский (ru)

Voici quelques exemples sur la façon d'utiliser VirtualTreeview pour Lazarus (testé sur win32). Ceci sont essentiellement collectés à partir du web écrit pour delphi, et à partir des tutoriels/documents par Philipp Frenzel et Mike Lischke. Les tutoriels/documents peuvent être téléchargé à partir de l'adresse http://www.soft-gems.net . Ci dessous quelqu'un trouverait seulement la manière rapide d'utiliser VirtualTreeview avec Lazarus, pas une explication. Pour des explications et de nombreuses autres fonctions/méthodes obtenir les documents officiels et le didacticiel.

Arbre de base Listview avec trois Colonnes

1. Installez le composant. Exécutez lazarus.

2. Déposez un composant TVirtualStringTree (Sous l'onglet Virtual Controls).

3. Aller à l'éditeur de source (Appuyez sur F12). Sous la clause Uses ajoutez une unité - appelée VirtualTrees (si elle n'est pas déjà là et que ce n'est pas VirtualStringTree). Ainsi, il peut ressembler à:

uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
  VirtualStringTree, VirtualTrees;

4. Aller à l'éditeur de fiches (Appuyez sur F12). Sélectionnez le composant Virtual Tree. Sur l'inspecteur d'objet cliquez sur Name, tapez VST et appuyez sur entrer. Cliquez sur Header (augmentez-le) -> Columns, cliquez sur le petit bouton situé à côté de "0 items". Cliquez 3 fois sur Add button pour ajouter 3 colonnes. Ne pas fermer cette fenêtre.

5. Sur la fenêtre d'édition de la colonne maintenant la 3ième colonne est sélectionnée. Aller à l'inspecteur d'objet. Cliquez sur Options (augmentez-le) -> fixez coAllowClicks à False.

6. Cliquez sur Text. Tapez Column2.

7. Cliquez sur Width, tapez 100 et appuyez sur enter.

8. Allez à la fenêtre d'édition de la colonne, selectionnez la 1ère et la 2ieme colonne, et fixez leur propriété comme ci-dessus (pour le champ Text, utiliser des noms différents, c'est à dire Column0, Column1).

9. Fermez la fenêtre d'édition de colonnes. Sélectionnez le composant Virtual Tree de la fiche. Sur l'inspecteur d'objet allez à Header -> Options (augmentez-le). Fixez hoVisible à True.

10. Faites défiler la liste jusqu'à Style fixez le à hsFlatButtons.

ExempleVirtualtreeView1.jpg

11. Faites défiler la liste jusqu'à TreeOptions(augmentez-le) -> MiscOption(augmentez-le), fixez toEditable à True. Fixez toGridExtensions à True.

12. Faites défiler la liste jusqu'à SelectionOptions(augmentez-le) -> fixez le toExtendedFocus à True. Fixez toMultiSelect à True. Sur le concepteur de fiche redimensionnez VST (composant Virtual Tree) pour obtenir le visuel de toutes les colonnes, si nécessaire.

13. Maintenant ajoutez 3 boutons sur la fiche. Obtenez les à partir de la palette de composants - Onglet standard (Label "OK" ).

14. CLiquez sur Button1, sur l'inspecteur d'object changez Caption avec AddRoot. Cliquez sur Button2, changez le caption avec AddChild. Changez le caption du Button3 avec Delete.

ExempleVirtualtreeView2.jpg

15. Gardez ceci ici et allez à l'éditeur de source(appuyez sur F12). Dans l'éditeur de source remplacez la ligne:

{$mode objfpc}{$H+} par {$MODE DELPHI}

16. Sous "implementation" coller les lignes suivantes:

type
  PTreeData = ^TTreeData;
  TTreeData = record
    Column0: String;
    Column1: String;
    Column2: String;
  end;

17. Allez au concepteur de fiche (Appuyez sur F12). sélectionnez VST. Allez à l'inspecteur d'objet, sélectionnez l'onglet évènements, défiler vers le bas vers l'évènement onChange. Double-cliquez sur le combobox. Coller ce qui suit:

procedure TForm1.VSTChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
 VST.Refresh;
end;

18. Faites défiler jusqu'à onFocusChanged. Double-cliquez et collez ce qui suit:

procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Column: TColumnIndex);
begin
  VST.Refresh;
end;

19. Faites défiler jusqu'à onFreeNode. Double-cliquez et collez ce qui suit:

procedure TForm1.VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
 Data: PTreeData;
begin
 Data:=VST.GetNodeData(Node);
 if Assigned(Data) then begin
   Data^.Column0 := '';
   Data^.Column1 := '';
   Data^.Column2 := '';
 end;
end;

20. Faites défiler jusqu'à onGetNodeDataSize. Double-cliquez et collez ce qui suit:

procedure TForm1.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
    NodeDataSize := SizeOf(TTreeData);
end;

21. Faites défiler jusqu'à onGetText. Double-cliquez et collez ce qui suit:

procedure TForm1.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
 Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
  Data: PTreeData;
begin
  Data := VST.GetNodeData(Node);
  case Column of
    0: CellText := Data^.Column0;
    1: CellText := Data^.Column1;
    2: CellText := Data^.Column2;
  end;
end;

22. Pressez sur F12 pour aller à concepteur de fiche. Double-cliquez sur le bouton AddRoot. Collez ce qui suit:

procedure TForm1.Button1Click(Sender: TObject);
Var
Data: PTreeData;
XNode: PVirtualNode;
Rand: Integer;
Begin
  Randomize;
  Rand := Random(99);
  XNode:=VST.AddChild(nil);
  
  if VST.AbsoluteIndex(XNode) > -1 then
  Begin
   Data := VST.GetNodeData(Xnode);
   Data^.Column0:= 'One ' + IntToStr(Rand);
   Data^.Column1:= 'Two ' + IntToStr(Rand + 10);
   Data^.Column2:= 'Three ' + IntToStr(Rand - 10);
  End; 
End;

23. Appuyez sur F9 pour exécuter le projet à vérifier. Cliquez sur AddRoot pour ajouter un nœud. Si c'est ok, le nœud sera ajouté sur VST.

ExempleVirtualtreeView3.jpg

24. Arrêtez l'exécution. Sur le concepteur de fiche double-cliquez sur le bouton intitulé addChild. Collez ce qui suit:

procedure TForm1.Button2Click(Sender: TObject);
var
  XNode: PVirtualNode;
  Data: PTreeData;
begin
  if not Assigned(VST.FocusedNode) then
    Exit;
    
    XNode := VST.AddChild(VST.FocusedNode);
    Data := VST.GetNodeData(Xnode);
    
    Data^.Column0:= 'Ch 1';
    Data^.Column1:= 'Ch 2';
    Data^.Column2:= 'Ch 3';

   VST.Expanded[VST.FocusedNode]:=True;
end;

25. Sur le concepteur de fiche double-cliquez sur le bouton intitulé Delete. Copiez ce qui suit:

procedure TForm1.Button3Click(Sender: TObject);
begin
  VST.DeleteSelectedNodes;
end;

26. Exécutez le projet en appuyant sur la touche F9 pour vérifier. Ajoutez quelques nœuds, nœuds fils et effacez les.

ExempleVirtualtreeView4.jpg

27. Essayez d'éditer un nœud. Sélectionnez un nœud et pressez sur F2, écrivez une nouvelle valeur. Si vous pouvez voir ce que vous tapez alors c'est OK. Sinon, lisez-dessous "Si l'édition d'une cellule ne peut être vue".

28. Pour obtenir que VST montre la nouvelle valeur après l'édition, allez au concepteur de fiche, sélectionnez VST. Double-cliquez sur le combobox de l'inspecteur d'objet -> Evenements -> OnNewText. Copiez ce qui suit:

procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Column: TColumnIndex; NewText: WideString);
Var
 Data: PTreeData;
begin
 Data := VST.GetNodeData(Node);
 Case Column of
  0: Data^.Column0:= NewText;
  1: Data^.Column1:= NewText;
  2: Data^.Column2:= NewText;
 End;
end;

Jusqu'à présent, l'exemple de l'utilisation de base se termine ici. Vous pouvez mettre quelques boutons de plus sur la fiche afin de tester quelques commandes indiquées ci-dessous. La suite serait de montrer les cases à cocher, les images, la couleur des caractères et l'ajout de combobox sur un noeud.


  • Une autre manière d'ajouter le nœud racine
procedure TForm1.Button8Click(Sender: TObject);
begin
  with VST do
  RootNodeCount:=RootNodeCount+1;
end;
  • Une autre façon d'ajouter un nœud enfant
procedure TForm1.Button9Click(Sender: TObject);
begin
  if Assigned(VST.FocusedNode) Then
  VST.ChildCount[VST.FocusedNode]:=VST.ChildCount[VST.FocusedNode]+1;
end;
  • Déterminer et effacer un enfant d'un nœud donné
procedure TForm1.Button4Click(Sender: TObject);
Var
 c: Integer;
begin
   if not Assigned(VST.FocusedNode) then
    Exit;
   If VST.HasChildren[VST.FocusedNode] then
   Begin
   c := VST.ChildCount[VST.FocusedNode];
   VST.DeleteChildren(VST.FocusedNode);
   ShowMessage('Number of deleted child:' + #13#10 + IntToStr(c));
   End;
end;
  • Effacer un nœud
procedure TForm1.Button5Click(Sender: TObject);
begin
{VST.Clear;  //Delete All Nodes}
   if not Assigned(VST.FocusedNode) then
    Exit;
   VST.DeleteNode(VST.FocusedNode);
end;
  • Rechercher et sélectionner un nœud
procedure TForm1.Button6Click(Sender: TObject);
Var
 XNode: PVirtualNode;
 Data: PTreeData;
begin
 XNode:= VST.GetFirst;

 while XNode <> nil do
 begin
  Data:=VST.GetNodeData(XNode);
   if Data^.Column0  = '1' then
    Begin
     VST.ClearSelection;
     VST.Selected[XNode]:=True;
     VST.SetFocus;
     break;
    End
    Else
    XNode:= VST.GetNextSibling(XNode);
 End;
End;
  • Determine Parent
procedure TForm1.Button13Click(Sender: TObject);
var
  XNode: PVirtualNode;
begin
  if not Assigned(VST.FocusedNode) then
    Exit;
  XNode:=VST.FocusedNode;
  while VST.GetNodeLevel(XNode) > 0 do
    Begin
    XNode := XNode.Parent;
    VST.Selected[XNode]:= True;
    End;
   VST.Refresh;
   VST.SetFocus;
end;
  • Tout rechercher
procedure TForm1.Button7Click(Sender: TObject);
Var
 XNode: PVirtualNode;
 Data: PTreeData;
begin
 If VST.GetFirst = nil then Exit;
 XNode:=nil;
 Repeat
 if XNode = nil then XNode:=VST.GetFirst Else XNode:=VST.GetNext(XNode);
  Data:=VST.GetNodeData(XNode);
   If (Data^.Column0 = '1') OR (Data^.Column1 = '1') OR (Data^.Column2 = '1') then
    Begin
     ShowMessage('Found at Node Level : ' + IntToStr(VST.GetNodeLevel(XNode)) );
     break;
    End;
  Until XNode = VST.GetLast();
end;
  • Insérer un nœud
procedure TForm1.Button12Click(Sender: TObject);
var
XNode: PVirtualNode;
begin
  If Assigned(VST.FocusedNode) then
  begin
      XNode := VST.InsertNode(VST.FocusedNode,amInsertBefore);
      // To Insert After Selected Node.
      {XNode := VST.InsertNode(VST.FocusedNode,amInsertAfter);}
      VST.Refresh;
  end;
end;
  • Fixer la hauteur d'un nœud
procedure TForm1.Button14Click(Sender: TObject);
begin
   If Assigned(VST.FocusedNode) then
   VST.NodeHeight[VST.FocusedNode] := 32;
end;
  • Sauvegarde et chargement

Un arbre simple (sans colonne) peut être sauvegardé et chargé ainsi:

VST.SaveToFile('filename.dat');
VST.LoadFromFile('filename.dat');


Pour enregistrer et charger l'exemple mentionné ci-dessus, placez 2 boutons sur la fiche, renommez le caption avec "Save" pour le 1er et "Load" pour le second. Sélectionnez VST, sur l'inspecteur d'objet -> TreeOptions -> StringOptions assurez-vous que toSaveCaptions est fixé à True. Allez à l'onglet évènements de l'inspecteur d'objet. Faites défiler la liste jusqu'à OnLoadNode, double-cliquez, puis collez:

procedure TForm1.VSTLoadNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream);
Var
 Data: PTreeData;
 Len: Integer;
begin
 Data := VST.GetNodeData(Node);
 Stream.read(Len, SizeOf(Len));
 SetLength(Data^.Column0, Len);
 Stream.read(PChar(Data^.Column0)^, Len);

 Stream.read(Len, SizeOf(Len));
 SetLength(Data^.Column1, Len);
 Stream.read(PChar(Data^.Column1)^, Len);

 Stream.read(Len, SizeOf(Len));
 SetLength(Data^.Column2, Len);
 Stream.read(PChar(Data^.Column2)^, Len);
end;

A nouveau sur l'onglet évènements de l'inspecteur d'objet - défiler vers le bas vers OnSaveNode, double-cliquez, puis collez:

procedure TForm1.VSTSaveNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream);
Var
 Data: PTreeData;
 Len: Integer;
begin
 Data := VST.GetNodeData(Node);
 Len := Length(Data^.Column0);
 Stream.write(Len, SizeOf(Len));
 Stream.write(PChar(Data^.Column0)^, Len);

 Len := Length(Data^.Column1);
 Stream.write(Len, SizeOf(Len));
 Stream.write(PChar(Data^.Column1)^, Len);

 Len := Length(Data^.Column2);
 Stream.write(Len, SizeOf(Len));
 Stream.write(PChar(Data^.Column2)^, Len);
end;

Sur le concepteur de fiche double-cliquez sur le bouton intitulé Save, collez:

procedure TForm1.Button10Click(Sender: TObject);
begin
 VST.SaveToFile('C:\vst.dat');
end;

Sur le concepteur de fiche double-cliquez sur le bouton intitulé Load, collez:

procedure TForm1.Button11Click(Sender: TObject);
begin
  VST.LoadFromFile('C:\vst.dat');
end;

Testez maintenant l'enregistrement et le chargement de l'arbre.

  • Problème de défilement

L'en-tête du treeview disparaît totalement ou partiellement lors du défilement. Je n'ai pas pu trouver une bonne solution pour cela. Une façon de surmonter ceci est de fixer la hauteur de l'en-tête à 0, puis d'utiliser un label général pour les colonnes. C'est bon tant qu'il y a peu de colonnes, et quelles sont toutes visibles sans défilement horizontal. Ou bien, la hauteur de l'en-tête peut être réglée à une valeur plus élevée de 25 ou 30. VST.Refresh peut être ajouté à l'évènement OnScroll.

  • Redimensionnement des colonnes

Il n'est pas possible de redimensionner une colonne en faisant glisser la souris sur l'en-tête de VST. Peut être c'est à cause d'un bug de l'en-tête ou j'ai oublié quelque chose. Si c'est à cause de l'en-tête, ça sera probablement fixé avec la prochaine version de Lazarus. Voir ce lien: http://bugs.freepascal.org/view.php?id=11209
Quoi qu'il en soit, il est possible de redimensionner la colonne à partir du code. Lorsque vous appuyez sur le bouton droit de la souris et déplacez la roulette vers le haut, la largeur de la colonne sélectionnée augmente et appuyez sur le bouton droit de la souris et déplacez la roulette vers le bas, pour diminuer la largeur de la colonne sélectionnée. Pour faire ceci:

1. Ajouter une variable dans l'éditeur de source nommé CurCol: Integer; Ainsi, le code ressemble à:

var
  Form1: TForm1; 
  CurCol: Integer; // <- Add this line only.

implementation

{ TForm1 }

2. Sur le concepteur de fiche double-cliquez sur le fiche pour générer l'évènement OnCreate. Dans la procédure OnCreate tapez Form1.OnMouseWheelUp:= et appuyez sur Ctrl+Shift+C, ceci va compléter le code et faire le squelette de l'évènement MouseWheelUp. Maintenant revenir à la procédure TForm1.FormCreate(Sender: TObject); et ajoutez un nouvel évènement pour MouseWheelDown. Tapez Form1.OnMouseWheelDown:= et appuyez sur Ctrl+Shift+C, pour générer l'évènement MouseWheelDown. La procédure FormCreate ressemble maintenant à :

procedure TForm1.FormCreate(Sender: TObject);
begin
    Form1.OnMouseWheelUp:=@Form1MouseWheelUp;
    Form1.OnMouseWheelDown:=@Form1MouseWheelDown;
end;

3. Remplissez la procédure TForm1.Form1MouseWheelUp ainsi:

procedure TForm1.Form1MouseWheelUp(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
begin
 If VST.Focused then
   if ssRight in Shift then
 VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width + 10;
end;

4. Remplissez la procédure TForm1.Form1MouseWheelDown ainsi:

procedure TForm1.Form1MouseWheelDown(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
begin
  If VST.Focused then
   if ssRight in Shift then
 VST.Header.Columns[CurCol].Width:= VST.Header.Columns[CurCol].Width - 10;
end;

5. Allez au concepteur de fiche (appuyez sur F12), sélectionnez VST, sur l'onglet des évènement de l'inspecteur d'objet faites défiler jusqu'à OnFocusChanged, double-cliquez et collez:

procedure TForm1.VSTFocusChanged(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex);
begin
  CurCol:=Column;
end;

Lorsque vous exécutez le programme, cliquez sur une colonne puis maintenez enfoncé le bouton droit de la souris et faire bouger la roulette vers le haut pour augmenter la largeur de la colonne, et le roulette vers le bas pour la diminuer. Vous devriez mettre au point les procédures ci-dessus si nécessaire. Ou bien, ajoutez un évènement au clavier avec quelque chose du genre "if (key=187) and (ssShift in Shift) then" pour surveiller le Shift + "+".



Checkbox


Sur le concepteur de fiche sélectionnez VST. Allez à:

  1. Inspecteur d'objets -> Propriétés -> CheckImageKind et sélectionnez ckDarkCheck.
  2. Inspecteur d'objets -> Propriétés -> TreeOptions -> MiscOptions -> toCheckSupport et la mettre à True.

Maintenant passer à l'onglet évènements.

  • Faites défiler jusqu'à OnInitNode. Double-cliquez et collez ce qui suit:
procedure TForm1.VSTInitNode(Sender: TBaseVirtualTree; ParentNode,
  Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
Var
 Level: Integer;
begin
    Level := VST.GetNodeLevel(Node);
    if Level = 0 then
    Node.CheckType:=ctCheckBox;

    if Level = 2 then
    Node.CheckType:=ctRadioButton;

    if Level = 1 then
    begin
    Node.CheckType:=ctTriStateCheckBox;
    Node.CheckState := csCheckedNormal;
    end;

    if Level = 3 then
    Node.CheckType:=ctButton;
end;

Lancez le programme, ajoutez le nœud racine et un nœud enfant puis l'enfant d'un enfant, et vérifiez si vous pouvez cocher et décocher correctement. Si non, fermez le programme. Allez à l'onglet évènements de l'inspecteur d'objets.

  • Faites défiler jusqu'à OnChecked, double-cliquez et collez:
procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
   vst.Refresh;
end;
  • Faites défiler jusqu'à OnChecking, double-cliquez et collez:
procedure TForm1.VSTChecking(Sender: TBaseVirtualTree; Node: PVirtualNode;
  var NewState: TCheckState; var Allowed: Boolean);
begin
 VST.Refresh;
end;

J'espère maintenant que c'est ok. Pour déterminer l'état du checkbox utilisez quelque chose comme:

If XNode.CheckState = csCheckedNormal then
ShowMessage('Checked.');

Les autres états sont:

csUncheckedNormal = unchecked and not pressed
csUncheckedPressed = unchecked and pressed
csCheckedNormal = checked and not pressed
csCheckedPressed = checked and pressed
csMixedNormal = 3-state check box and not pressed
csMixedPressed = 3-state check box and pressed

Les autres types sont:

ctNone
ctTriStateCheckBox
ctCheckBox
ctRadioButton
ctButton
  • Pour capturer le clic du bouton Checkbox (ctButton)

Allez à l'onglet évènements de l'inspecteur d'objets. Faites défiler jusqu'à OnChecked, double-cliquez et collez:

procedure TForm1.VSTChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
 if Node.CheckType = ctButton then
 ShowMessage('Ok.');
 VST.Refresh;
end;

Fin de checkbox.



Image & Font Colour


To show image on VST nodes, a list of image should be created.

  • Go to the Component Palette -> Common Controls. Select and drop a TImageList component on the form. Right click on the component icon and select ImageList Editor. Click on Add button and and select some images (at least 3 for now), then click on tick button to accept and close the ImageList Editor. By the way, there are some nice images you can download from http://www.famfamfam.com/lab/icons/silk/
  • Now on the Form Designer select VST, and on Object Inspector's Properties tab, scroll to Images and select ImageList1
  • On Object Inspector's Events tab scroll to OnGetImageIndex, double click and paste:
procedure TForm1.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean;
  var ImageIndex: Integer);
begin
if Kind in [ikNormal , ikSelected] then // Either Selected or not
 begin
  if Column = 0 then                    // if 1st Column
    ImageIndex:=0;                      // 1st Image of the ImageList1

  if Column = 1 then                    // if 2nd Column
    ImageIndex:=1;                      // 2nd Image of the ImageList1

  if Sender.FocusedNode = Node then     // Only show if Focused
   if Column =2 then                    // if 3rd Column
    ImageIndex:=2;                      // 3rd Image of the ImageList1
  end;
 {Sender.NodeHeight[node]:=40; //If Image is big}
end;
Font Colour

On the Form Designer select VST, and on Object Inspector's Events tab, scroll to OnPaintText, double click and paste:

procedure TForm1.VSTPaintText(Sender: TBaseVirtualTree;
  const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
  TextType: TVSTTextType);
Var
 Data: PTreeData;
begin
 Data := VST.GetNodeData(Node);
 
 if Data^.Column0 = 'sky' then
  TargetCanvas.Font.Color:=clBlue;
  
 if Column = 1 then
 begin
   TargetCanvas.Font.Color:=clRed;
   TargetCanvas.Font.Style:= Font.Style + [fsItalic];
 end;
 
 if Column = 2 then
 begin
//  ImageList1.Draw(Form1.Canvas,-1,-1,2); {draw top left of form, 3rd image of ImageList1??}
  TargetCanvas.Font.Size:= 9;
  TargetCanvas.Font.Color:=clHighlightText;
 end;
end;

Image & Font Colour ends here.

Adding A Combobox

  • I guess you have an open project on Lazarus IDE having VST on it and can edit the nodes. If not see the "Basic Tree Listview With 3 Columns" above, and atleast complete steps 1 to 21.
  • Bellow there is an unit file named combo. Copy that unit and save as combo.pas inside the project directory. Under your program's uses clause add combo. So it may look like:
uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
  VirtualStringTree, VirtualTrees, combo;
  • The combo.pas unit
unit combo;

{$mode delphi}

interface

uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,
  VirtualStringTree, VirtualTrees, messages, windows, StdCtrls;

type
  TStringEditLink = class(TInterfacedObject, IVTEditLink)
  private
    FEdit: TWinControl;
    FTree: TVirtualStringTree;
    FNode: PVirtualNode;
    FColumn: Integer;
  protected
    procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  public
    destructor Destroy; override;
    function BeginEdit: Boolean; stdcall;
    function CancelEdit: Boolean; stdcall;
    function EndEdit: Boolean; stdcall;
    function GetBounds: TRect; stdcall;
    function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall;
    procedure ProcessMessage(var Message: TMessage); stdcall;
    procedure SetBounds(R: TRect); stdcall;
  end;

implementation

destructor TStringEditLink.Destroy;
begin
  FEdit.Free;
  inherited;
end;

procedure TStringEditLink.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
    case Key of
    VK_ESCAPE:
      begin
        FTree.CancelEditNode;
        Key := 0;
        FTree.setfocus;
      end;
      VK_RETURN:
      begin
       PostMessage(FTree.Handle, WM_KEYDOWN, VK_DOWN, 0);
       Key := 0;
       FTree.EndEditNode;
       FTree.setfocus;
      end;
     End; //case
end;


function TStringEditLink.BeginEdit: Boolean;
begin
  Result := True;
  //FEdit.Height:=(FTree.DefaultNodeHeight - 1); //Needed for editbox. Not combo
  FEdit.Show;
  TComboBox(FEdit).DroppedDown:=True;
  FEdit.SetFocus;
end;

function TStringEditLink.CancelEdit: Boolean;
begin
  Result := True;
  FEdit.Hide;
end;


function TStringEditLink.EndEdit: Boolean;
var
  S: WideString;
begin
  Result := True;
  S:= TComboBox(FEdit).Text;
  FTree.Text[FNode, FColumn] := S;

  FTree.InvalidateNode(FNode);
  FEdit.Hide;
  FTree.SetFocus;
end;


function TStringEditLink.GetBounds: TRect;
begin
  Result := FEdit.BoundsRect;
end;


function TStringEditLink.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean;
begin
  Result := True;
  FTree := Tree as TVirtualStringTree;
  FNode := Node;
  FColumn := Column;

  FEdit.Free;
  FEdit := nil;

  FEdit := TComboBox.Create(nil);
   with FEdit as TComboBox do
     begin
          Visible := False;
          Parent := Tree;
          Items.Add('Google');
          Items.Add('Yahoo');
          Items.Add('Altavista');
          OnKeyDown := EditKeyDown;
      end;
end;


procedure TStringEditLink.ProcessMessage(var Message: TMessage);
begin
  FEdit.WindowProc(Message);
end;


procedure TStringEditLink.SetBounds(R: TRect);
var
  Dummy: Integer;

begin
  FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right);
  FEdit.BoundsRect := R;
end;

End.
  • After saving the file, on the Form Designer select VST and on Object Inspector's Properties, scroll to TreeOptions -> MiscOptions, set toEditable to True. Then get to TreeOptions -> SelectionOptions, set toExtendedFocus to True.
  • Switch to Object Inspector's Events tab. Scroll to OnCreateEditor, double click and paste:
procedure TForm1.VSTCreateEditor(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink);
begin
  EditLink:=TStringEditLink.Create;
end;
  • On Object Inspector's Events tab. Scroll to OnNewText, double click and paste:
procedure TForm1.VSTNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Column: TColumnIndex; NewText: WideString);
Var
Data: PTreeData;
begin
Data := VST.GetNodeData(Node);
Case Column of
 0: Data^.Column0:= NewText;
 1: Data^.Column1:= NewText;
 2: Data^.Column2:= NewText;
End;
end;

Run program, select a node and press F2 to get combobox. On pressing Enter new value should appear on the node.

If Cell Editing Can't Be Seen


Open VirtualStringTree.pas unit file (if you are still on the above example project, right click on VirtualStringTree under Uses clause and select Find Declaration. This opens the file on next tab. Go to that file's tab.). Get to the "function TStringEditLink.BeginEdit: Boolean; stdcall;". It looks like:

    
function TStringEditLink.BeginEdit: Boolean; stdcall;

// Notifies the edit link that editing can start now. Descentants may cancel node edit
// by returning False.

begin
  Result := not FStopping;
  if Result then
  begin
    FEdit.Show;
    FEdit.SelectAll;
    FEdit.SetFocus;
  end;
end;

Now add "FEdit.Height:=18;". It should look like:

function TStringEditLink.BeginEdit: Boolean; stdcall;

// Notifies the edit link that editing can start now. Descentants may cancel node edit
// by returning False.

begin
  Result := not FStopping;
  if Result then
  begin
    FEdit.Show;
    FEdit.SelectAll;
    FEdit.SetFocus;
    FEdit.Height:=18; // <--- Added this line.
  end;
end;

Save the file (press Ctrl + S). If you are on the example project, close this (Project -> Close Project). Click on Tools -> Configure "Build Lazarus" ... Select Clean Up + Build All and then click on the Build button. After compile Lazarus should be restarted. Now open the example project and try to edit node on VST. This time it should be ok.
Thank you.
--Rabiul 21:37, 20 October 2008 (CEST)
Alhamdulillah.


Programando en Pascal - Spanish tutorial focused on FPC/Lazarus, hosted in Wikibooks.