[toc]
QT窗口默认可以直接鼠标点住窗口的标题栏实现拖拽移动,如果需要鼠标点住窗口客户区域实现窗口的拖拽移动,可以通过QMouseEvent事件来实现。
.h文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #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; };
|
.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
| void Widget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { m_bDrag = true; mouseStartPoint = event->globalPos(); windowTopLeftPoint = this->frameGeometry().topLeft(); } } void Widget::mouseMoveEvent(QMouseEvent *event) { if(m_bDrag) { QPoint distance = event->globalPos() - mouseStartPoint; this->move(windowTopLeftPoint + distance); } } void Widget::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { m_bDrag = false; } }
|