TTreeView/ru

From Free Pascal wiki
Revision as of 14:32, 20 June 2020 by Zoltanleo (talk | contribs) (Created page with "{{TTreeView}} [https://lazarus-ccr.sourceforge.io/docs/lcl/comctrls/ttreeview.html '''TTreeView'''] image:ttreeview.png является графическим элеме...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

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

TTreeView ttreeview.png является графическим элементом управления, который представляет иерархическое представление информации. Каждый элемент может иметь несколько подпунктов.

Элемент можно развернуть, чтобы показать подэлементы, если таковые существуют, и свернуть, чтобы скрыть подэлементы.

Добавление нового элемента в коде

Используйте TTreeView.Items.AddChild или AddChildObject.

Создание TreeView, который загружает элементы только при раскрытии узла

Чтобы добавить значок раскрытия к узлу без подпунктов, используйте:

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. Затем установите обработчик события OnExpanding. В любом случае вы должны вернуться независимо от того, может ли быть выполнено раскрытие узла или нет; и если может, вы должны добавить подпункты к узлу. Если раскрытие узла не может быть выполнено, символ раскрытия будет автоматически удален, даже если ранее для HasChildren было установлено значение true.

Краткий пример использования TTreeview

Вот быстрый пример на коленке - я тестировал на Windows Lazarus 0.9.26:

Создаем новое приложение. На форму Form1 добавляем пустой treeview, button1 с заголовком "Add Child"(Добавить дочерний элемент) и button2 с надписью "Delete"(Удалить). Для событий кнопок OnClick назначаем следующий код, компилируем и запускаем.

Код:

procedure TForm1.Button1Click(Sender: TObject);
var 
  i: integer;
  s: string;
begin
  //если нет узлов, создаем корневой узел с родителем nil
  if TreeView1.Items.Count = 0 then
  begin
    Treeview1.Items.Add (nil,'Root Node');
    exit;
  end;
 
  //задаем простой текст для каждого нового узла - Node1, Node2 и т.д.
  i := treeview1.Items.Count;
  s := 'Node ' + inttostr(i);
  //добавляем новый узел в текущий выделенный узел
  if TreeView1.Selected <> nil then
    Treeview1.Items.AddChild(Treeview1.Selected ,s);
end;
 
procedure TForm1.Button2Click(Sender: TObject);

    //процедура рекурсивного удаления узлов
  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 treeview1.Selected.HasChildren then
    if messagedlg( 'Удалить узел и все его дочерние элементы ?',mtConfirmation, [mbYes,mbNo],0 ) <> mrYes then 
      exit;
  DeleteNode(TreeView1.Selected);
end;

При запуске treeview пуст. Если вы нажмете кнопку "Add Child"(Добавить дочерний элемент), будет создан корневой узел. После этого дочерний элемент будет добавлен в любой выделенный узел по нажатию "Add Child"(Добавить дочерний элемент). Кнопка "Delete" удалит текущий выделенный узел. Если у него нет дочерних элементов, он удалит его сразу, если есть - сначала спросит.

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;
  Node.Data := nil;
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