Java教程

qt重写鼠标事件移动窗体

本文主要是介绍qt重写鼠标事件移动窗体,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

 

 

 

 

头文件

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

    QPoint mousePoint;
    bool m_mousePressed;
    void mouseMoveEvent(QMouseEvent *event);//鼠标按下事件
    void mousePressEvent(QMouseEvent *event);//鼠标释放事件
    void mouseReleaseEvent(QMouseEvent *event);//鼠标松开事件

源文件
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
    m_mousePressed = false;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(m_mousePressed && (event->buttons() && Qt::LeftButton)){
        this->move(event->globalPos()- mousePoint);
        event->accept(); //accept ()函数用来告诉Qt,事件处理函数“接收”了这个事件,不要再传递;
    }
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        m_mousePressed = true;
        mousePoint = event->globalPos() - this->pos();
        event->accept();
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    m_mousePressed = false;
}
这篇关于qt重写鼠标事件移动窗体的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!