我們知道,要實現窗口移動可以直接鼠標點住窗口的標題欄實現拖拽移動,這是窗口默認的行為,在QT中的事件響應函數為moveEvent。
但是現實中經常需要鼠標點住窗口客戶區域實現窗口的拖拽移動,代碼實現如下:
Widget.h
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#ifndef
WIDGET_H #define WIDGET_H #include <QWidget> class QMouseEvent; class Widget : public QWidget { Q_OBJECT public : Widget(QWidget *parent = 0 ); ~Widget(); protected : //拖拽窗口 void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private : bool m_bDrag; QPoint mouseStartPoint; QPoint windowTopLeftPoint; }; #endif // WIDGET_H |
Widget.cpp
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include
"Widget.h"
#include <QMouseEvent> Widget::Widget(QWidget *parent) : QWidget(parent) , m_bDrag( false ) { setWindowTitle( "窗口拖拽移動" );
setFixedSize(640, 480); } Widget::~Widget() { } /* QPoint QMouseEvent::pos() const Returns the position of the mouse cursor, relative to the widget that received the event. If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion. */ //拖拽操作 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->globalPos() - mouseStartPoint; //QPoint distance = event->pos() - mouseStartPoint; //改變窗口的位置 this ->move(windowTopLeftPoint + distance); } } void Widget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_bDrag = false ; } } |
需要注意的一點:一般定位鼠標坐標使用的是event->pos()和event->globalPos()兩個函數,
event->globalPos()獲取的鼠標位置是鼠標偏離電腦屏幕左上角(x=0,y=0)的位置;
event->pos()獲取的位置是主窗口(widget窗口)左上角(邊框的左上角,外左上角)相對於電腦屏幕的左上角的(x=0,y=0)偏移位置
一般不采用前者,使用前者,拖動准確性較低且會產生抖動。