Win7系統不得不說是非常好用的,也是目前為止占用份額最大的操作系統,其中win7有個效果,將窗體拖動到頂部時會自動最大化,拖動到左側右側時會自動半屏顯示,再次拖動窗體到其他位置,會重新恢復之前的大小,這個效果還是比較人性化的,大大方便了很多用戶的操作習慣。
在Qt中,如果是無邊框窗體,(有邊框窗體和操作系統窗體效果一致)並沒有相關的API接口來實現這個效果,必須自己寫代碼來模擬這個效果,原理很簡單,綁定事件過濾器,自動計算當前無邊框窗體的位置和鼠標按下去的坐標,當到達頂部或者左側右側時,自動設置該窗體的geometry即可。
為了復用代碼,我這里綁定的全局事件過濾器,這樣只需要無邊框窗體界面設置兩行即可,無需重復編碼。
無邊框窗體代碼:
this->setProperty("canMove", true); this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
核心代碼:
#include "appinit.h" #include "qapplication.h" #include "qdesktopwidget.h" #include "qevent.h" #include "qwidget.h" #include "qdebug.h" AppInit *AppInit::self = 0; AppInit::AppInit(QObject *parent) : QObject(parent) { } bool AppInit::eventFilter(QObject *obj, QEvent *evt) { QWidget *w = (QWidget *)obj; if (!w->property("canMove").toBool()) { return QObject::eventFilter(obj, evt); } //存儲桌面寬高以及全屏/左側半屏/右側半屏 區域 static int deskWidth = qApp->desktop()->availableGeometry().width(); static int deskHeight = qApp->desktop()->availableGeometry().height(); static QRect fullRect = qApp->desktop()->availableGeometry(); static QRect leftRect = QRect(0, 0, deskWidth / 2, deskHeight); static QRect rightRect = QRect(deskWidth / 2, 0, deskWidth / 2, deskHeight); bool autoRect = w->property("autoRect").toBool(); static QPoint mousePoint; static bool mousePressed = false; 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; //計算全局坐標 int x = event->globalPos().x(); int y = event->globalPos().y(); int offset = 10; //如果Y坐標在桌面頂部,則自動最大化 //如果X坐標在桌面左側,則自動左側半屏幕 //如果X坐標在桌面右側,則自動右側半屏幕 //自動變化后記住當前窗體是自動產生的位置,以便下次恢復時自動應用變化前的位置 if (!autoRect) { //存儲最后一次的位置,自動矯正負數的坐標 int oldX = w->geometry().x(); oldX = oldX < 0 ? 0 : oldX; int oldY = w->geometry().y(); oldY = oldY < 0 ? 0 : oldY; QRect oldRect = QRect(oldX, oldY, w->geometry().width(), w->geometry().height()); if (y < offset) { w->setProperty("autoRect", true); w->setProperty("oldRect", oldRect); w->setGeometry(fullRect); } else if (x < offset) { w->setProperty("autoRect", true); w->setProperty("oldRect", oldRect); w->setGeometry(leftRect); } else if (x > (deskWidth - offset)) { w->setProperty("autoRect", true); w->setProperty("oldRect", oldRect); w->setGeometry(rightRect); } } return true; } else if (event->type() == QEvent::MouseMove) { if (mousePressed && (event->buttons() && Qt::LeftButton)) { if (!autoRect) { w->move(event->globalPos() - mousePoint); } else { QRect oldRect = w->property("oldRect").toRect(); w->setProperty("autoRect", false); w->setGeometry(oldRect); } return true; } } return QObject::eventFilter(obj, evt); } void AppInit::start() { qApp->installEventFilter(this); }