Qt5:无边框窗口拖动

在窗口程序中,无边框窗口程序一般需要特殊处理才能拖动

Qt中,要实现无边框窗口的拖动,需要重新实现 mousePressEvent 和 mouseMoveEvent 俩虚函数

 1 void Widget::mousePressEvent(QMouseEvent *event)
 2 {
 3     if (event->button() == Qt::LeftButton) {
 4         pos = event->globalPos() - frameGeometry().topLeft();
 5         event->accept();
 6     }
 7 }
 8 
 9 void Widget::mouseMoveEvent(QMouseEvent *event)
10 {
11     if (event->buttons() & Qt::LeftButton) {
12         move(event->globalPos() - pos);
13         event->accept();
14     }
15 }

在上述简短的代码中,主要实现的功能就是,鼠标左键被按下时,记录下鼠标相对于窗口左上角的位置,拖动时获取鼠标当前的全局位置,并减去鼠标相对于窗口左上角的

位置,此时获取的就是窗口左上角拖动后应该在的全局位置,然后调用move函数,将窗口移动到正确的位置。这样,无边框窗口移动就实现了。

另外,frameGeometry().topLeft() 这个函数可以换成 pos()  , 两者返回相同 。有一点要注意的是 ,不能把 pos()  写成 event->pos() , 在实验的时候,

我犯了这个错误 , 结果花了一下午终于才查出来。

原文地址:https://www.cnblogs.com/wowk/p/3163280.html