qt 控件拖动

头文件 .h

#ifndef C_H
#define C_H

#include
#include "ui_c.h"
#include

class c : public QWidget
{
    Q_OBJECT

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

protected:
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
private:
    Ui::cClass ui;
    bool m_move;
    QPoint m_startPoint;
    QPoint m_windowPoint;
};

源文件 .cpp

c::c(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    //给是否移动的标志初始化为false.
    m_move = false;
}

c::~c()
{

}
void c::mousePressEvent(QMouseEvent *event)
{
    //当鼠标左键点击时.
    if (event->button() == Qt::LeftButton)
    {
        m_move = true;
        //记录鼠标的世界坐标.
        m_startPoint = event->globalPos();
        //记录窗体的世界坐标.
        m_windowPoint = this->frameGeometry().topLeft();
    }
}
void c::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        //移动中的鼠标位置相对于初始位置的相对位置.
        QPoint relativePos = event->globalPos() - m_startPoint;
        //然后移动窗体即可.
        this->move(m_windowPoint + relativePos );
    }
}
void c::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        //改变移动状态.
        m_move = false;
    }
}

你可能感兴趣的:(qt 控件拖动)