How to drag custom widgets?

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

I added 4 of my custom widgets in a vertical layout. Now I want to drag custom widgets inside of me. To be more clear, if I dragged the last widget and placed it in the first position, then the first widget should go to the second posit and the last widget (which is dragged) should go to the first position. (the same as dragging and dropping items in the List view). Can anyone suggest me a way to drag and drop custom widgets. enter image description here

+3
source share
1 answer

You need to override the mousePressEvent , mouseMoveEvent and mouseReleaseEvent widget that you want to drag or set an event filter on them.
Keep the cursor position in mousePressEvent and move the widget in mousePressEvent the distance the cursor moves from the press point. Remember to clear the cursor position in mouseReleaseEvent . The exact code depends on how you want the widget to look when you drag it and how other widgets should behave when you drag 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; } 
+1
source

Source: https://habr.com/ru/post/951967/


All Articles