QT中实现窗口的拖拽主要利用的是三个事件的重写
mousePressEvent
重写后检测到鼠标按下左键时记录按下的point的坐标以及拖拽的窗口的坐标point
mouseMoveEvent
重写后判断若是在拖动状态,记录鼠标移动的位置差,即目前的位置减去鼠标原来的位置,并将窗口move到窗口的坐标point加上目前的位置差的最新位置
mouseReleaseEvent
重写后在鼠标左键放下后判断拖拽结束
.h文件
#ifndef DRAGWIDGET_H
#define DRAGWIDGET_H
#include <QtWidgets/QWidget>
#include "ui_dragwidget.h"
#include <QMouseEvent>
class DragWidget : public QWidget
{
Q_OBJECT
public:
DragWidget(QWidget *parent = Q_NULLPTR);
protected:
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
private:
Ui::DragWidgetClass ui;
bool is_drag_ = false;
QPoint mouse_start_point_;
QPoint window_start_point_;
};
#endif //DRAGWIDGET_H
.cpp文件
#include "dragwidget.h"
DragWidget::DragWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
void DragWidget::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
is_drag_ = true;
//获得鼠标的初始位置
mouse_start_point_ = event->globalPos();
//获得窗口的初始位置
window_start_point_ = this->frameGeometry().topLeft();
}
}
void DragWidget::mouseMoveEvent(QMouseEvent* event)
{
//判断是否在拖拽移动
if (is_drag_)
{
//获得鼠标移动的距离
QPoint move_distance = event->globalPos() - mouse_start_point_;
//改变窗口的位置
this->move(window_start_point_ + move_distance);
}
}
void DragWidget::mouseReleaseEvent(QMouseEvent* event)
{
//放下左键即停止移动
if (event->button() == Qt::LeftButton)
{
is_drag_ = false;
}
}