头文件
//鼠标拖动窗体移动
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
bool m_bDrag;
QPoint mouseStartPoint;
QPoint windowTopLeftPoint;
源文件
//实现鼠标拖拽移动
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_bDrag = true;
//获得鼠标的初始位置
mouseStartPoint = event->globalPos();
//mouseStartPoint = event->pos();
//获得窗口的初始位置
windowTopLeftPoint = this->frameGeometry().topLeft();
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if(m_bDrag)
{ //这里if语句判断,让鼠标在特定控件上进行拖动才有效,比如自绘标题栏控件
if(!ui->label->underMouse()){
return;
}
//获得鼠标移动的距离
QPoint distance = event->globalPos() - mouseStartPoint;
//QPoint distance = event->pos() - mouseStartPoint;
//改变窗口的位置
this->move(windowTopLeftPoint + distance);
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_bDrag = false;
}
}