QT drag the window to achieve learning

The most basic is to calculate three values, a set value, the coordinates of the mouse relative to the upper left corner of the window, two change values, the absolute coordinates of a mouse on the screen and the absolute coordinate of the upper left corner of the window. In a single movement of the mouse relative coordinates of the upper left corner of the window is the same, so it may be calculated according to the coordinates of the moving train window.

Code is as follows:
.h files should add function

void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);

QPoint mouse_relative_pos;

.cpp file implementation

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    QPoint mouse_global_pos = event->globalPos();  //取到鼠标的绝对位置
    QPoint window_top_left = this->geometry().topLeft();  //取到窗口左上角的绝对位置

    QPoint move_point = mouse_global_pos - mouse_relative_pos;  //得到窗口左上角的绝对位置

    this->move(move_point);
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    QPoint mouse_global_pos = event->globalPos();
    QPoint window_top_left = this->geometry().topLeft();
    mouse_relative_pos =  mouse_global_pos - window_top_left;  //得到鼠标相对于窗口左上角的坐标,移动时,这个值是一直不变的
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    mouse_relative_pos.setX(0);
    mouse_relative_pos.setY(0);
}

Guess you like

Origin blog.51cto.com/11753138/2409644