Qt 設定Qt::FramelessWindowHint 後介面無法移動問題的一種解決方案
阿新 • • 發佈:2020-12-13
Qt 設定Qt::FramelessWindowHint
後介面無法移動問題的一種解決方案
從別人程式碼中摘出來的
思路
1. 寫一個單例
2. 重寫事件過濾器
3. qApp 註冊過濾器
程式碼
.h
#ifndef APPINIT_H #define APPINIT_H #include <QObject> #include <QMutex> class AppInit : public QObject { Q_OBJECT public: explicit AppInit(QObject *parent = 0); static AppInit *Instance() { static QMutex mutex; if (!self) { QMutexLocker locker(&mutex); if (!self) { self = new AppInit; } } return self; } void start(); protected: bool eventFilter(QObject *obj, QEvent *evt); private: static AppInit *self; }; #endif // APPINIT_H
.cpp
#include "appinit.h" #include "qapplication.h" #include "qevent.h" #include "qwidget.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 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; 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); } void AppInit::start() { // 讓整個應用程式註冊過濾器 qApp->installEventFilter(this); }
使用
main.cpp
#include <QtWidgets/QApplication> #include "Client.h" #include "appinit.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); AppInit::Instance()->start(); Client w; // 設定"CanMove"屬性 w.setProperty("CanMove", true); w.showFullScreen(); return a.exec(); }
由於在過濾器中是使用"CanMove"屬性來判斷的,
QWidget *w = (QWidget *)obj;
if (!w->property("CanMove").toBool()) {
return QObject::eventFilter(obj, evt);
}
所以使用的時候只要設定"CanMove"屬性為"ture"就可以了
setProperty("CanMove", true);