1 QMouseEvent
1.1 特别说明
QMouseEvent没啥要注意的,就是对于mouseMoveEvent,默认情况下,触发事件需要点击一下,才能触发。可设置为自动触发:setMouseTracking(true);
。
2 通过QMouseEvent事件实现窗口移动
实现起来还是比较简单的。
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
protected:
//拖拽窗口,重写三个虚函数
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
private:
bool m_bDrag;
QPoint mouseStartPoint;
QPoint windowTopLeftPoint;
};
#endif // WIDGET_H
实现文件:
#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget),
m_bDrag(false)
{
ui->setupUi(this);
setWindowTitle("窗口拖拽移动");
setFixedSize(640, 480);
}
Widget::~Widget()
{
delete ui;
}
//拖拽操作
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->pos() - mouseStartPoint;
QPoint distance = event->globalPos() - mouseStartPoint;
//改变窗口的位置
this->move(windowTopLeftPoint + distance);
/*
注意:一般定位鼠标坐标使用的是event->pos()和event->globalPos()两个函数,
event->pos()鼠标相对于当前活动窗口左上角的位置
event->globalPos()获取的鼠标位置是鼠标偏离电脑屏幕左上角(x=0,y=0)的位置;
一般不采用前者,使用前者,拖动准确性较低且会产生抖动。
*/
}
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_bDrag = false;
}
}
需要特别注意:在鼠标移动过程中必须通过buttons()来判断是哪个按键按下。因为button函数: