Qt重新實現QMouseEvent實現自定義視窗可拖動
阿新 • • 發佈:2018-12-03
(1)pro檔案中加入
QT += gui
(2)h檔案的類中加入標頭檔案:
#include <QMouseEvent>
類中加入函式和變數宣告:
protected: void mouseMoveEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); private: QPoint mLastMousePosition; bool mMoving;
(3)cpp檔案中加入滑鼠事件相關函式的定義
void MainWindow::mousePressEvent(QMouseEvent* event) { if(event->button() == Qt::LeftButton) { mMoving = true; mLastMousePosition = event->globalPos(); } } void MainWindow::mouseMoveEvent(QMouseEvent* event) { if( event->buttons().testFlag(Qt::LeftButton) && mMoving) { this->move(this->pos() + (event->globalPos() - mLastMousePosition)); mLastMousePosition = event->globalPos(); } } void MainWindow::mouseReleaseEvent(QMouseEvent* event) { if(event->button() == Qt::LeftButton) { mMoving = false; } }
轉載自https://blog.csdn.net/qq_28093585/article/details/78483019