#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。而且在全局做任何事情都可以。
时间: 2024-11-08 04:16:34