간만에 퀴즈가 아닌 팁 하나 올립니다.
누가 TStringGrid의 row나 col을 drag-drop으로 이동할수 없냐는 궁금증을 가져서
함 간단히 만들어 봤았습니다.
주요 메소드
TCustomGrid에보면 MoveRow , MoveColumn이라는 메소드가 있는데..
이놈들이 proected되어있구 TStringGrid에서는 public으로 되어있지 않네요...
그래서 TMyGrid라는 놈을 이용하여 위 함수를 쉽게 사용하도록 변경했습니다.
class TMyGrid : public TStringGrid
{
public:
void __fastcall MoveRow(int from,int to)
{
TCustomGrid::MoveRow(from,to); //protected 메소드
}
void __fastcall MoveCol(int from,int to)
{
TCustomGrid::MoveColumn(from,to);//protected 메소드
}
};
//---------------------------------------------------------------------------
DragDrop으로 Grid의 row및 column이동하기
아래 코드는 FixedRow나 FixedCol이 둘다 1 이라는 가정하에 코딩하였으며
Fixed-Cell을 클릭해서 move할때만 drag-drop이 동작하도록 했습니다.
bool bRowMove; //Row이동인지 Col이동인지 판단변수
int iDragSoruceRow;
int iDragSoruceCol;
void __fastcall TForm1::StringGrid1MouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if(Shift.Contains(ssLeft))
{
StringGrid1->MouseToCell(X,Y,iDragSoruceCol,iDragSoruceRow);
if(iDragSoruceCol<1 && iDragSoruceRow>0)bRowMove=true;
else bRowMove=false;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::StringGrid1MouseMove(TObject *Sender,
TShiftState Shift, int X, int Y)
{
if(Shift.Contains(ssLeft))
{
if(bRowMove)
{
if(iDragSoruceRow>0 && iDragSoruceCol==0)
StringGrid1->BeginDrag(true,0);
}
else
{
if(iDragSoruceRow==0 && iDragSoruceCol>0)
StringGrid1->BeginDrag(true,0);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::StringGrid1DragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept)
{
int iRow,iCol;
StringGrid1->MouseToCell(X,Y,iCol,iRow);
if(bRowMove)Accept=(iRow>0 && iRow!=iDragSoruceRow);
else Accept=(iCol>0 && iCol!=iDragSoruceCol);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::StringGrid1DragDrop(TObject *Sender,
TObject *Source, int X, int Y)
{
int iTargetRow,iTargetCol;
StringGrid1->MouseToCell(X,Y,iTargetCol,iTargetRow);
TStringList *lst=new TStringList;
if(bRowMove)
{
lst->Assign(StringGrid1->Rows[iDragSoruceRow]);
((TMyGrid *)StringGrid1)->MoveRow(iDragSoruceRow,iTargetRow);
StringGrid1->Rows[iTargetRow]=lst;
}
else
{
lst->Assign(StringGrid1->Cols[iDragSoruceCol]);
((TMyGrid *)StringGrid1)->MoveCol(iDragSoruceCol,iTargetCol);
StringGrid1->Cols[iTargetCol]=lst;
}
delete lst;
}
//---------------------------------------------------------------------------
TCustotmGrid 의 MoveRow와 MoveColumn은 왜 protected로 해놓았는지 이해가 잘 안되네요..
그럼..