Mirror

How to drag and drop TPanels within a scrollbox to rearrange the order (Views: 38)


Problem/Question/Abstract:

All I want to do is to allow the user to drag/ drop panels within a scrollbox to rearrange the order. They are initially created in alpha order by caption anf pointers stored in a stringlist. When the user moves one it is moved in the stringlist, the scrollbox is cleared (note: the panels cannot be freed because they contain info) and re-parented in stringlist sequence. If you do more than one move, the resulting sequence of the panels in the scrollbox seems completely random, and certainly bears no resemblance to the sequence in the stringlist! I have tried doing this by index up from and downto zero; neither works.

Answer:

All your trouble comes from using the alTop style for the panels. Simply set it to alNone and size and position the panels in code, using their SetBounds method.

procedure TForm1.FormCreate(Sender: TObject);
var
  iCount: integer;
  APanel: TPanel;
  y: Integer;
begin
  AStrList := TStringList.Create;
  y := 0;
  for iCount := 0 to 4 do
  begin
    APanel := TPanel.Create(Self);
    with APanel do
    begin
      Name := 'P' + IntToStr(iCount);
      Align := alNone;
      OnMouseDown := PanelMouseDown;
      OnDragOver := PanelDragOver;
      OnDragDrop := PanelDragDrop;
      SetBounds(0, y, scrollbox1.clientwidth, height);
      Inc(y, height);
    end;
    AStrList.AddObject(APanel.Caption, APanel);
  end;
  for iCount := 0 to (AStrList.Count - 1) do
    TPanel(AStrList.Objects[iCount]).Parent := ScrollBox1;
end;

procedure TForm1.PanelDragDrop(Sender, Source: TObject; X, Y: Integer);
var
  iFrom, iTo, iCount: integer;
begin
  iFrom := AStrList.IndexOfObject(TPanel(Sender));
  iTo := AStrList.IndexOfObject(TPanel(Source));
  AStrList.Move(iFrom, iTo);
  y := 0;
  for iCount := 0 to (AStrList.Count - 1) do
    with TPanel(AStrList.Objects[iCount]) do
    begin
      Top := y;
      Inc(y, Height);
    end;
end;

<< Back to main page