Qt实现用鼠标拖拽对话框

来源:互联网 发布:最优化方法 解可新 编辑:程序博客网 时间:2024/05/16 02:05

Qt实现用鼠标拖拽对话框

在QWidget类中定义了两个函数

void mousePressEvent(QMouseEvent *);//鼠标点击时执行的槽函数void mouseMoveEvent(QMouseEvent *);//鼠标移动时执行的槽函数

继承自QWidget的类中可以重定义这两个函数,从而实现拖拽对话框的操作
头文件

#include<qwidget.h>#include<QMouseEvent>class Dlg : public QWidget{Q_OBJECTpublic:Dlg(QWidget *parent = 0);public slots:void mouseMoveEvent(QMouseEvent *);void mousePressEvent(QMouseEvent *);private:QPoint dragPoint;//记录坐标};

源文件

#include"dlg.h"Dlg::Dlg(QWidget *parent): QWidget(parent){//自行实现}void Dlg::mousePressEvent(QMouseEvent *event){if (event->button() == Qt::LeftButton){    dragPoint = event->globalPos() - frameGeometry().topLeft();//记录鼠标点坐标和对话框左上角坐标的差值    event->accept();    }}void Dlg::mouseMoveEvent(QMouseEvent *event){    if (event->buttons()&Qt::LeftButton){    move(event->globalPos() - dragPoint);//move的参数是对话框左上角的坐标,根据差值和当前鼠标点计算出移动的对话框左上角的坐标值    event->accept();    }}

注意

event->buttons()&Qt::LeftButton

改成

event->button()==Qt::LeftButton

将没有效果

button()和buttons()差别

Qt::MouseButton QMouseEvent::button() constReturns the button that caused the event.Note that the returned value is always Qt::NoButton for mouse move events.See also buttons() and Qt::MouseButton.Qt::MouseButtons QMouseEvent::buttons() constReturns the button state when the event was generated. The button state is a combination of Qt::LeftButton, Qt::RightButton, Qt::MidButton using the OR operator. For mouse move events, this is all buttons that are pressed down. For mouse press and double click events this includes the button that caused the event. For mouse release events this excludes the button that caused the event.See also button() and Qt::MouseButton.

因为对于QMouseEvent::button()来说,鼠标移动的时候他的值恒为Qt::NoButton

Note that the returned value is always Qt::NoButton for mouse move events.
0 0