Qt事件处理窗体跟着鼠标选中窗体时跟着鼠标移动
class MoveFrme :public QDialog
{
public:
MoveFrme(Qwidget *pParent =null):QDialog(pParent){};
~MoveFrme(){};
protected:
void mousePressEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
private:
bool m_bPressed;//鼠标按下标志
QPoint m_ptPress;//鼠标按下的初始位置
};
void MoveFrme::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton)
{
m_bPressed = true;
m_ptPress = e->globalPos() - this->pos(); //转为具体的坐标位置
e->accept();
this->move(this->pos());
}
}
void MoveFrme::mouseMoveEvent(QMouseEvent *e)
{
if (m_bPressed && (e->buttons() && Qt::LeftButton))
{
this->move(e->globalPos() - m_ptPress); //移动事件进行进行位置计算
e->accept();
}
}
void MoveFrme::mouseReleaseEvent(QMouseEvent *)
{
m_bPressed = false;
}