How to Drag and Drop Custom Widgets?
Asked Answered
S

1

3

I have created my own custom widget and I want to support internal drag and drop for the widgets.

I have added 4 of my custom widgets in a vertical box layout. Now i want to drag and drop the custom widgets internally. To be more clear, If i drag the last widget and drop it in the first position, then the first widget has to move to the second positon and the last widget (which is dragged) has to move to first position. (same like drag and drop of the items in the List view). Can anyone suggest me a way to drag and drop of the custom widgets.enter image description here

Smithy answered 8/12, 2013 at 12:20 Comment(0)
C
1

You need to reimplement mousePressEvent, mouseMoveEvent and mouseReleaseEvent methods of a widget you want to drag or install an event filter on them.
Store the cursor position in mousePressEvent and move the widget in mousePressEvent to the distance the cursor moved from the press point. Don't forget to clear the cursor position in the mouseReleaseEvent. The exact code depends of how you want the widget to look when is being dragged and how other widgets should behave when drag/drop the widget. In the simplest case it will look like this:

void mousePressEvent(QMouseEvent* event)
{      
  m_nMouseClick_X_Coordinate = event->globalX();
  m_nMouseClick_Y_Coordinate = event->globalY();    
};

void mouseMoveEvent(QMouseEvent* event)
{
  if (m_nMouseClick_X_Coordinate < 0)
    return;

  const int distanceX = event->globalX() - m_nMouseClick_X_Coordinate;
  const int distanceY = event->globalY() - m_nMouseClick_Y_Coordinate;

  move(x() + distanceX, y() + distanceY());
};

void mouseReleaseEvent(QMouseEvent* event)
{
  m_nMouseClick_X_Coordinate = -1;
}
Canaille answered 30/7, 2014 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.