The following is the source code of the base class, which inherits the desired moving window class from the base class.
Header file:
/************************************************************************//*basewidget.h *//*************** /#ifndef Basewidget_h#define Basewidget_h#include < Qwidget>class basewidget:public qwidget{q_objectpublic:basewidget (qwidget *parent = 0); ~BaseWidget ();p rotected: void Mousepressevent (qmouseevent *event); void Mousemoveevent (qmouseevent *event); void Mousereleaseevent (QMouseEvent *event); bool m_moving;//is used to mark whether the mouse moves qpoint m_offset;private:}; #endif//Basewidget_h
CPP file:
/************************************************************************//* BaseWidget.cpp *//************************************************************************/#include "BaseWidget.h "#include <QMouseEvent> #include <QDesktopWidget> #include <qapplication>basewidget::basewidget ( Qwidget *parent): Qwidget (Parent,qt::framelesswindowhint), m_moving (false) {}basewidget::~basewidget () {}void Basewidget::mousepressevent (qmouseevent *event) {if ((Event->button () = = Qt::leftbutton)) {m_moving = True;m_offset = Event->pos ();}} void Basewidget::mousemoveevent (Qmouseevent *event) {if (m_moving) {//method 1:qdesktopwidget* Desktop = qapplication:: Desktop (); Qrect Windowrect (Desktop->availablegeometry ()); Qrect Widgetrect (This->geometry ()); Qpoint Point (Event->globalpos ()-m_offset);//The following is to prevent the window from being dragged out of visible range outside//left if (point.x () <= 0) {point = Qpoint (0,point.y ());} Right int y = Windowrect.bottomright (). Y ()-this->size (). height ();F (Point.y () >= y && widgetrect.topleft (). Y () >= y) {point = Qpoint (Point.x (), y);} Upper if (point.y () <= 0) {point = Qpoint (Point.x (), 0);} the bottom int x = Windowrect.bottomright (). x ()-This->size (). width (); if (Point.x () >= x && widgetrect.topleft () . x () >= x) {point = Qpoint (X,point.y ());} Move (point),///method 2://can be determined by Qrect Windowrect whether it contains (contains) Qrect widgetrect to move//Here is no code}//if just ask to move the window, with the following code can be implemented// Move (Event->globalpos ()-m_offset);} void Basewidget::mousereleaseevent (qmouseevent*event) {if (Event->button () = = Qt::leftbutton) m_moving = false;}
QT window Untitled is moved on the desktop and cannot be moved outside the viewable range