如何使用TVirtualStringTree进行增量搜索

时间:2013-06-10 18:28:49

标签: delphi virtualtreeview tvirtualstringtree

我正在学习TVirtualStringTree用法,必须实施增量搜索。当用户将字符输入TEdit时,我想将焦点节点移动到树中的第一个合格节点。

我正在阅读我能找到的所有演示和示例代码,但似乎找不到这个的起点。任何人都可以让我开始使用伪代码或更好吗?

2 个答案:

答案 0 :(得分:5)

控件已支持增量搜索。您不需要添加任何编辑控件;刚开始输入树控件,它将选择下一个匹配的节点。根据需要设置IncrementalSearchIncrementalSearchDirectionIncrementalSearchStartIncrementalSearchTimeout属性。

要选择与给定条件匹配的第一个节点,请使用IterateSubtree。编写一个匹配TVTGetNodeProc签名的方法,根据您的搜索条件检查单个节点。将为树中的每个节点调用它,如果节点匹配,则应将Abort参数设置为true。使用IterateSubtree的第三个参数(名为Data)将搜索字词与任何其他搜索条件一起传达给您的回调函数。

答案 1 :(得分:4)

我已经删除了一些不必要的代码,但是你去了:

unit fMyForm;

interface

uses
  Windows, Messages, Forms, StdCtrls, VirtualTrees, StrUtils;

type
  TfrmMyForm = class(TForm)
    vstMyTree: TVirtualstringTree;
    myEdit: TEdit;
    procedure myEditChange(Sender: TObject);
  private
    procedure SearchForText(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean);
  end;

  PDatastructure = ^TDatastructure;
  TDatastructure = record
    YourFieldHere : Widestring;
  end;

implementation

{$R *.dfm}

procedure TfrmMyForm.SearchForText(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean);
var
  NodeData: PDatastructure; //replace by your record structure
begin
  NodeData := Sender.GetNodeData(Node);
  Abort := AnsiStartsStr(string(data), NodeData.YourFieldHere); //abort the search if a node with the text is found.
end;

procedure TfrmMyForm.myEditChange(Sender: TObject);
var
  foundNode : PVirtualNode;
begin
  inherited;
  //first param is your starting point. nil starts at top of tree. if you want to implement findnext
  //functionality you will need to supply the previous found node to continue from that point.
  //be sure to set the IncrementalSearchTimeout to allow users to type a few characters before starting a search.
  foundNode := vstMyTree.IterateSubtree(nil, SearchForText, pointer(myEdit.text));

  if Assigned (foundNode) then
  begin
    vstMyTree.FocusedNode := foundNode;
    vstMyTree.Selected[foundNode] := True;
  end;
end;

end.