expand/collapse TreeView only by node image click
I have on my form a TreeView with a lots of items/nodes. When I double click a item of a node I run a procedure (depending of the clicked item).My problem is that I want it to expand/collapse only when I cl开发者_如何转开发ick on the icon of the node ( the + or - sign), not if I double click an item
similar question
You may use the AllowCollapse and AllowExpand parameters of the OnCollapsing and OnExpanding events, to prevent the node from being collapsed or expanded.
Combine that with the appropiate logic to recognize the part of the node being clicked on. If the generating click was on the icon, let the action progress, if not, then ignore it (setting AllowXxxxx:=false)
But be careful not to break keyboard navigation. So you will need to check the origin of the event, and in case of a keyboard event (cursor left/right) leave the action progress.
To keep track of the originator event, capture the OnMouseDown and OnKeyDown events, and set an internal indicator of the type of the latest one received, so you may check for the later OnCollapsing and OnExpanding event process.
I know, it's not a good solution but it works :).
procedure TForm1.TWDblClick(Sender: TObject);
begin
TW.Items.BeginUpdate;
TW.Selected.Expanded:=not TW.Selected.Expanded;
TW.Items.EndUpdate;
end;
unit TreeViewNav;
interface
uses
SysUtils, Classes, Controls, ComCtrls, Messages;
type
TNavTreeView = class(TTreeView)
private
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk);
message WM_LBUTTONDBLCLK;
protected
FNoCollapse: Boolean;
function CanCollapse(Node: TTreeNode): Boolean; override;
end;
implementation
{ TNavTreeView }
function TNavTreeView.CanCollapse(Node: TTreeNode): Boolean;
begin
Result := not FNoCollapse and inherited;
FNoCollapse := False;
end;
procedure TNavTreeView.WMLButtonDblClk(var Message: TWMLButtonDblClk);
var
PX, PY: Integer;
HT: THitTests;
begin
with Message do
if (Width > 32768) or (Height > 32768) then
with CalcCursorPos do
begin
PX := X;
PY := Y;
end
else
begin
PX := XPos;
PY := YPos;
end;
HT := GetHitTestInfoAt(PX, PY);
if htOnItem in HT then
begin
FNoCollapse := True;
end;
inherited;
end;
end.
If you are using VirtalTreeView
There is a setting that controls the double click expand in TreeOptions.MiscOptions
toToggleOnDblClick Toggle node expansion state when it is double clicked.
精彩评论