首页 > 代码库 > 通过全局设置过滤器,就能让所有窗口都可移动,而不是都要继承指定QDialog

通过全局设置过滤器,就能让所有窗口都可移动,而不是都要继承指定QDialog

#include "appinit.h"#include <QMouseEvent>#include <QApplication>#include <QWidget>AppInit::AppInit(QObject *parent) : QObject(parent){    mousePressed = false;    qApp->installEventFilter(this);}void AppInit::load(){}bool AppInit::eventFilter(QObject *obj, QEvent *evt){    QWidget *w = (QWidget *)obj;    if(evt->type () == QEvent::KeyPress)        {            QKeyEvent * event = static_cast<QKeyEvent *>(evt);            if(event->key () == Qt::Key_Escape)            {                return true;            }        }    if (!w->property("CanMove").toBool()) {        return QObject::eventFilter(obj, evt);    }    QMouseEvent *event = static_cast<QMouseEvent *>(evt);    if (event->type() == QEvent::MouseButtonPress) {        if (event->button() == Qt::LeftButton) {            mousePressed = true;            mousePoint = event->globalPos() - w->pos();            return true;        }    } else if (event->type() == QEvent::MouseButtonRelease) {        mousePressed = false;        return true;    } else if (event->type() == QEvent::MouseMove) {        if (mousePressed && (event->buttons() && Qt::LeftButton)) {            w->move(event->globalPos() - mousePoint);            return true;        }    }    return QObject::eventFilter(obj, evt);}

这个方法的最大特点是,不影响其它类层次的设计,而不必强行指定继承我的QDialog。而且在全局做任何事情都可以。

 

通过全局设置过滤器,就能让所有窗口都可移动,而不是都要继承指定QDialog