Перетащите элементы управления каплей в сетке

StackOverflow https://stackoverflow.com/questions/5359948

  •  27-10-2019
  •  | 
  •  

Вопрос

Я дурачился с перетаскиванием и сбрасыванием элементов управления на панели сетки в Delphi 2010. Переместите панель/кнопку/все, что содержимое из одной ячейки в другую ячейку. Замена существующих или замененных мест. Я не выяснил, как я знаю, какая ячейка была снята, потому что они работают с индексами столбцов, а также индексами строк.

Так что, если у меня есть GridPanel, которая имеет 3 столбца и 3 ряда, и у меня есть кнопка в ячейке 1/1 ... и я перетаскиваю эту кнопку с 1/1 в 3/3, как я могу получить место для этой ячейки из перетаскивания мероприятие? Я получаю x, y координирует на каплю, но как я могу определить ячейку из этого?

Это было полезно?

Решение

Вы можете использовать TGridPanel.CellRect Чтобы получить ограничивающий прямоугольник для каждой из ячейки. Вот пример того, как использовать CellRect:

// GP: TGridPanel
// This is the "OnDragDrop" handler.

procedure TForm13.GPDragDrop(Sender, Source: TObject; X, Y: Integer);
var DropPoint: TPoint;
    CellRect: TRect;
    i_col, i_row: Integer;
begin
  if Source = Panel1 then // Simple test, is this a drop I want to handle?
  begin
    DropPoint := Point(X, Y); // Where did the suer drop? We need this so we can easily call PtInRect
    for i_col := 0 to GP.ColumnCollection.Count-1 do
      for i_row := 0 to GP.RowCollection.Count-1 do
      begin
        CellRect := GP.CellRect[i_col, i_row]; // Get the bounding rect for Col[i_col, i_row]
        if PtInRect(CellRect, DropPoint) then
        begin
          // Panel1 was dropped over Cell[i_col, i_row]
        end;
      end;
  end;
end;

Другие советы

Основываясь на ответе Космина (которая является хорошей отправной точкой, но не работает в реальной жизни).

Мой код находится в C ++, но, поскольку это «клон» ответа Consmin, пользователи Delphi могут легко понять его (и посмотреть, что было изменено).
PS: Обратите внимание, что я перетаскиваю tpanels вместо Tbuttons (очень незначительное изменение).

void __fastcall TfrmVCL::ButtonDragDrop(TObject *Sender, TObject *Source, int X, int Y)
{
  TRect CurCellRect;
  TRect DestCellRect;
  int Col;
  int Row;
  int srcCol; int srcRow;
  int destCol; int destRow;
  int srcIndex; int destIndex;
  TPanel *SrcBtn;
  TPanel *DestBtn;

  SrcBtn = dynamic_cast<TPanel *>(Source);
  if (SrcBtn)
     {
     int ColCount = GridPnl->ColumnCollection->Count ;
     int RowCount = GridPnl->RowCollection->Count ;

     // SOURCE
     srcIndex = GridPnl->ControlCollection->IndexOf( SrcBtn );
     srcCol   = GridPnl->ControlCollection->Items[ srcIndex ]->Column;  // the column for the dragged button
     srcRow   = GridPnl->ControlCollection->Items[ srcIndex ]->Row;

     // DESTINATION
     // we get coordinates of the button I drag onto
     DestBtn= dynamic_cast<TPanel *>(Sender);
     if (!DestBtn) return;
     destIndex    = GridPnl->ControlCollection->IndexOf( DestBtn );
     destCol      = GridPnl->ControlCollection->Items[ destIndex ]->Column;  // the column for the dragged button
     destRow      = GridPnl->ControlCollection->Items[ destIndex ]->Row;
     DestCellRect = GridPnl->CellRect[ destCol ][ destRow ];

     // Check all cells
     for ( Col = 0 ; Col < ColCount ; Col++ )
        {
        for ( Row = 0 ; Row < RowCount ; Row++ )
           {
             // Get the bounding rect for this cell
             CurCellRect = GridPnl->CellRect[ Col ][ Row ];

             if (IntersectRect_ForReal(DestCellRect, CurCellRect))
                {
                GridPnl->ControlCollection->Items[srcIndex]->SetLocation(Col, Row, false);
                return;
                }
             else
               lblCurCellRect->Caption= "NO HIT";
           }
        }
     }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top