Qt自由拖动无边框窗体(eventFilter事件过滤实现)

效果如下:

做项目中为了美观,经常需要对窗口标题栏,按钮进行自定义,因此常使用隐藏系统默认窗口边框选项 Qt::FramelessWindowHint,为使窗口能被随意拖动,使用Qt中的事件过滤器,重载eventFilter(QObject *obj, QEvent *evt)函数,每次拖拽事件发生时,返回当前事件触发窗体QObject进入事件过滤事件中,并对该窗体位置进行改变。

拖拽事件过滤在主函数中进行加载。每个需要支持拖拽的窗口设置自定义属性:this->setProperty("canMove",true);当属性canMove为真时支持拖拽。即在Main函数中加载过滤后不需要在窗体代码中引用拖拽模块。

窗体可拖拽功能模块代码:

appmove.h

#ifndef APPMOVE_H
#define APPMOVE_H

#include <QObject>
#include <QMutex>
#include <QEvent>
#include <QWidget>
#include <QApplication>
#include <QMouseEvent>

class AppMove:public QObject
{
public:
public:
    explicit AppMove(QObject *parent = 0);

    void start();

protected:
    bool eventFilter(QObject *obj, QEvent *evt);

};

#endif // APPMOVE_H

appmove.cpp

#include "appmove.h"

AppMove::AppMove(QObject *parent) : QObject(parent)
{

}

bool AppMove::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 AppMove::start()
{
    qApp->installEventFilter(this);
}

主函数main:

#include "widget.h"
#include "appmove.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    AppMove move;
    move.start();

    Widget w;
    w.show();

    return a.exec();
}

DEMO下载地址:

https://github.com/zjgo007/QtDemo/tree/master/MoveWidgeticon-default.png?t=LA92https://github.com/zjgo007/QtDemo/tree/master/MoveWidget

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵喵叫的猴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值