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; }
source share