重写窗口的两个事件函数mousePressEvent和mouseMoveEvent即可:
在mousePressEvent 中,按下鼠标左键时,记录窗口坐标,其中窗口坐标的计算是由鼠标事件获取到鼠标在整个屏幕中的坐标(ev->globalpos()),然后再使用pos()获取到鼠标在窗口内的相对位置,两者之差就是窗口在整个屏幕上的坐标x,y。如下:
![](https://img-blog.csdnimg.cn/img_convert/66a1506c2669e0fd7f3f2f3b6918fb5c.png)
在Qt中可以直接使用ev->globalPos() - pos(),两者相减获取到程序窗口在屏幕上的坐标(x,y);
在mouseMoveEvent中,事件是不断实时触发的,通过move方法传入实时计算的窗口目标位置,然后实时刷新移动窗口;
void Dialog::mousePressEvent(QMouseEvent *ev)
{
//鼠标左键按下时记录坐标
if(ev->button() == Qt::LeftButton){
// ev->globalPos() 获取鼠标的全局坐标(在整个屏幕中)
// pos()获取的是鼠标在窗口中的相对位置坐标(在程序窗口内)
// last_pos为前者与后者的差(鼠标的绝对坐标-鼠标在窗口内的相对坐标偏移),也就是窗口左上角在桌面的坐标x,y
last_pos = ev->globalPos()-pos();
qDebug()<<"last_pos:"<<last_pos;
}
return QDialog::mousePressEvent(ev);
}
void Dialog::mouseMoveEvent(QMouseEvent *ev)
{
if( ev->buttons() & Qt::LeftButton){ //注意这里是&按位与,不是&&,只有鼠标左键按下时才触发
move(ev->globalPos()-last_pos); // 实时计算窗口的x,y坐标
// qDebug()<<"move"<<ev->globalPos()-last_pos;
last_pos = ev->globalPos() - pos();
}
return QDialog::mouseMoveEvent(ev);
}