通用移動類,目標就是爲了實現放入任意的控件之後,支持鼠標拖動,在容器中或者父類中拖動,這個應用場景很是多,好比在地圖上放置的設備,須要用戶自行按下拖動到指定的合適的位置,而後保存設備的位置座標到數據庫,下次打開直接加載,在一些安防項目、電力項目、環境監測等上面大量運用,有時候設備對應了多種類型,之前作的辦法是將這個移動的代碼直接封裝在對應設備的自定義控件中,有個巨大缺點就是若是再新增長一個控件,又須要重複的代碼加到控件中才行,能否將這個功能獨立出來,只要傳入控件就行呢,固然能夠,好比我寫過不少自定義控件,如今須要控件放到某個容器中能自由拖動,只須要new出通用移動類來就行。 項目開源地址:https://gitee.com/feiyangqingyun/QWidgetDemolinux
#ifndef MOVEWIDGET_H #define MOVEWIDGET_H /** * 通用控件移動類 做者:feiyangqingyun(QQ:517216493) 2019-9-28 * 1:能夠指定須要移動的widget * 2:可設置是否限定鼠標左鍵拖動 * 3:支持任意widget控件 */ #include <QWidget> #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT MoveWidget : public QObject #else class MoveWidget : public QObject #endif { Q_OBJECT public: explicit MoveWidget(QObject *parent = 0); protected: bool eventFilter(QObject *watched, QEvent *event); private: QPoint lastPoint; //最後按下的座標 bool pressed; //鼠標是否按下 bool leftButton; //限定鼠標左鍵 QWidget *widget; //移動的控件 public Q_SLOTS: //設置是否限定鼠標左鍵 void setLeftButton(bool leftButton); //設置要移動的控件 void setWidget(QWidget *widget); }; #endif // MOVEWIDGET_H
#include "movewidget.h" #include "qevent.h" #include "qdebug.h" MoveWidget::MoveWidget(QObject *parent) : QObject(parent) { lastPoint = QPoint(0, 0); pressed = false; leftButton = true; widget = 0; } bool MoveWidget::eventFilter(QObject *watched, QEvent *event) { if (widget != 0 && watched == widget) { QMouseEvent *mouseEvent = (QMouseEvent *)event; if (mouseEvent->type() == QEvent::MouseButtonPress) { //若是限定了只能鼠標左鍵拖動則判斷當前是不是鼠標左鍵 if (leftButton && mouseEvent->button() != Qt::LeftButton) { return false; } //判斷控件的區域是否包含了當前鼠標的座標 if (widget->rect().contains(mouseEvent->pos())) { lastPoint = mouseEvent->pos(); pressed = true; } } else if (mouseEvent->type() == QEvent::MouseMove && pressed) { //計算座標偏移值,調用move函數移動過去 int offsetX = mouseEvent->pos().x() - lastPoint.x(); int offsetY = mouseEvent->pos().y() - lastPoint.y(); widget->move(widget->x() + offsetX, widget->y() + offsetY); } else if (mouseEvent->type() == QEvent::MouseButtonRelease && pressed) { pressed = false; } } return QObject::eventFilter(watched, event); } void MoveWidget::setWidget(QWidget *widget) { if (this->widget == 0) { this->widget = widget; this->widget->installEventFilter(this); } } void MoveWidget::setLeftButton(bool leftButton) { this->leftButton = leftButton; }