How to Drag and Drop Custom Widgets?

China☆狼群 提交于 2019-12-12 15:44:40

问题


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.


回答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;
}


来源:https://stackoverflow.com/questions/20453308/how-to-drag-and-drop-custom-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!