Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus - Drag and Drop items in the same TListBox

2 Posts
1 Users
0 Reactions
3,135 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

This is just an example how you can use Drag and Drop to change the order of items is a TListBox or a TCheckListBox.

First we define a global variable, this can be a property of TForm1 for example;

  DraggingItemNumber : integer;

Next we define 3 procedures for the ListBox events "OnMouseDown", "OnDragDrop", "OnDragOver".

We use OnMouseDown to identify that the user clicked a mouse button (this can be left or right mouse button), where we determine if a proper item has been selected and store that item number in the global variable.

The OnDragOver event is used to make sure the item has a place to drop, on it's own control. If that's the case we gladly accept a potential drop (mouse cursor changes).

The onDragDrop even is used to "receive" the dropped item and, if everything is legit, move the dragged item to the new location.

procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  DraggingItemNumber := ListBox1.ItemAtPos(Point(X,Y), true);
  if (DraggingItemNumber>-1) and (DraggingItemNumber<ListBox1.Count) then
    ListBox1.BeginDrag(true)
  else
    begin
      ListBox1.BeginDrag(False);
      DraggingItemNumber:=-1;
    end;
end;     procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
var ItemUnderMouse:integer;
begin
  ItemUnderMouse := ListBox1.ItemAtPos(Point(X,Y), true);
  if (ItemUnderMouse>-1) and (ItemUnderMouse<ListBox1.Count) and (DraggingItemNumber>-1) then
    listShares.Items.Move(DraggingItemNumber,ItemUnderMouse);
end; procedure TForm1.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
var ItemUnderMouse:integer;
begin
  if Sender=Source then
    begin
      ItemUnderMouse := ListBox1.ItemAtPos(Point(X,Y), true);
      Accept:=(ItemUnderMouse>-1) and (ItemUnderMouse<ListBox1.Count);
    end
  else
    Accept:=false;
end;    


   
ReplyQuote
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

Side note, to make just Clicking (selecting) an item possible:

Set DragMode:=dmAutomatic for the ListBox or CheckListBox.


   
ReplyQuote
Share: