Qt 窗口拖拽移动实现

众所周知,要实现窗口移动可以直接鼠标点住窗口的标题栏实现拖拽移动,这是窗口默认的行为,在QT中的事件响应函数为moveEvent。

但是现实中经常需要鼠标点住窗口客户区域实现窗口的拖拽移动,代码实现如下:

Widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 

class QMouseEvent;
class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();

protected:
    //拖拽窗口
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);

private:
    bool        m_bDrag;
    QPoint      mouseStartPoint;
    QPoint      windowTopLeftPoint;
};

#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include 


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , m_bDrag(false)
{
    setWindowTitle("窗口拖拽移动");
    setFixedSize(640, 480);
}

Widget::~Widget()
{

}

/* QPoint QMouseEvent::pos() const
    Returns the position of the mouse cursor, relative to the widget that received the event.
    If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.
 */

//拖拽操作
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_bDrag = true;
        //获得鼠标的初始位置
        mouseStartPoint = event->globalPos();
        //mouseStartPoint = event->pos();
        //获得窗口的初始位置
        windowTopLeftPoint = this->frameGeometry().topLeft();
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(m_bDrag)
    {
        //获得鼠标移动的距离
        QPoint distance = event->globalPos() - mouseStartPoint;
        //QPoint distance = event->pos() - mouseStartPoint;
        //改变窗口的位置
        this->move(windowTopLeftPoint + distance);
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_bDrag = false;
    }
}

需要注意的一点:一般定位鼠标坐标使用的是event->pos()和event->globalPos()两个函数,

event->globalPos()获取的鼠标位置是鼠标偏离电脑屏幕左上角(x=0,y=0)的位置;

event->pos()获取的位置是主窗口(widget窗口)左上角(边框的左上角,左上角)相对于电脑屏幕的左上角的(x=0,y=0)偏移位置

一般不采用前者,使用前者,拖动准确性较低且会产生抖动



Qt学习路线:Qt开发技术栈

Qt资料领取:Qt资料领取(视频教程+文档+代码+项目实战)

展开阅读全文

页面更新:2024-03-15

标签:窗口   左上角   拖动   边框   坐标   函数   电脑屏幕   位置   代码   资料

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top