Qt 設置Qt::FramelessWindowHint 后界面無法移動問題的一種解決方案


Qt 設置Qt::FramelessWindowHint后界面無法移動問題的一種解決方案

從別人代碼中摘出來的

效果

思路

1. 寫一個單例
2. 重寫事件過濾器
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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM