3

I have a Virtual Treeview (e.g. TVirtualStringTree).

  • The user can select a row
  • but it would be nice if they could also do the intuitiave thing of clicking "nowhere" to select no row

enter image description here

Note: Of course multiselect is off; because they can only select zero or one items

MCRE:

procedure TForm6.FormCreate(Sender: TObject);
var
    vst: TVirtualStringTree;
begin
    vst := VirtualStringTree1;

    vst.RootNodeCount := 5;
    vst.TreeOptions.SelectionOptions := vst.TreeOptions.SelectionOptions + [toFullRowSelect];
    vst.Header.Options := vst.Header.Options + [hoVisible];
    vst.Header.Columns.Add;
    vst.Header.Columns.Add;
    vst.Header.Columns.Add;
    vst.Header.Columns.Add;
    vst.Header.Columns.Add;
end;
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219

2 Answers2

1

This should work out-of-the-box if toAlwaysSelectNode is not set and toMultiSelect is set in TreeOption.SelectionOptions. Tested wit latest source.

In other cases simply call ClearSelection():

procedure TVisibilityForm.VST2MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if TBaseVirtualTree(Sender).GetNodeAt(Point(X, Y)) = nil then
    TBaseVirtualTree(Sender).ClearSelection();
end;
Joachim Marder
  • 782
  • 5
  • 12
  • 1
    It wreaks havoc with `toRightClickSelect`. It's one of those hacks that probably leads to chasing down edge-cases forever. Also, i assume you mean *"`toMultiSelect` is not set in **TreeOptions.SelectionOptions**"* (because using `toMultiSelect` means you don't have to do anything special - clicking the empty background unselects already) – Ian Boyd Mar 22 '19 at 14:51
  • _"because using toMultiSelect means you don't have to do anything special"_ That's what I meant with it works out-of-the-box. – Joachim Marder Mar 22 '19 at 20:53
  • Yes, the right click selection behavior seems to be a critical point in every TreeView control. Feel free to submit more details in an issue at GitHub. – Joachim Marder Mar 22 '19 at 21:00
0

This procedure in OnMouseDown should work regardless of the settings, you just need toRightClickSelect in TreeOptions.SelectionsOptions for right click selection, otherwise it doesn't work properly.

procedure VSTMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Button in [mbLeft, mbRight] then
    VST.FocusedNode := VST.GetNodeAt(X, Y);

  if Assigned(VST.FocusedNode) then
    VST.TreeOptions.PaintOptions := VST.TreeOptions.PaintOptions - [toAlwaysHideSelection]
  else
    VST.TreeOptions.PaintOptions := VST.TreeOptions.PaintOptions + [toAlwaysHideSelection];
end;
Triber
  • 1,525
  • 2
  • 21
  • 38