date:
updated:

Qt无边框窗口拖拽和阴影


在这里插入图片描述

作者:hackett
微信公众号:加班猿

无边框窗口的实现

只需要一行代码即可实现

1
this->setWindowFlags(Qt::FramelessWindowHint);

image-20201102191116019

代码及运行效果:

image-20201102191340908

无边框窗口能拖拽实现

先要去QWidget里面找到鼠标事件函数

image-20201102192216514

理一下坐标的位置情况:

左上角:屏幕的左上角

中间的窗口:程序的窗口

箭头:鼠标位置

坐标位置满足:x = y - z

image-20201102193018846

在Designer里面拖一个Widget出来叫shadowWidget

image-20201102195257871

shadowWidget的颜色为灰色,我们选个自己喜欢的背景色方便查看

image-20201102200730118

接下来我们要重写鼠标事件函数才能让拖拽功能生效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Widget::mouseMoveEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠标相当于桌面左上角的位置,鼠标全局位置
QPoint x = y - this->z;
this->move(x);
}

void Widget::mousePressEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠标相当于桌面左上角的位置,鼠标全局位置
QPoint x = this->geometry().topLeft();//窗口左上角位于桌面左上角的位置,窗口位置
this->z = y - x; //定值,不变
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
this->z = QPoint(); //鼠标松开获取当前的坐标
}

最终效果变为鼠标可拖动的窗口:

image-20201102201326910

源码:

main.cpp

1
2
3
4
5
6
7
8
9
10
11
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();

return a.exec();
}

widget.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "widget.h"
#include "ui_widget.h"
#include <QMouseEvent>
#include <QWidget>
#include <QGraphicsDropShadowEffect>

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);

this->setWindowFlags(Qt::FramelessWindowHint);

QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();

shadow->setBlurRadius(5); //边框圆角
shadow->setColor(Qt::black);//边框颜色
shadow->setOffset(0); //不偏移

ui->shadowWidget->setGraphicsEffect(shadow);

this->setAttribute(Qt::WA_TranslucentBackground); //父窗口设置透明,只留下子窗口
}

Widget::~Widget()
{
delete ui;
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠标相当于桌面左上角的位置,鼠标全局位置
QPoint x = y - this->z;
this->move(x);
}

void Widget::mousePressEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠标相当于桌面左上角的位置,鼠标全局位置
QPoint x = this->geometry().topLeft();//窗口左上角位于桌面左上角的位置,窗口位置
this->z = y - x; //定值,不变
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
this->z = QPoint(); //鼠标松开获取当前的坐标
}

widget.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
explicit Widget(QWidget *parent = 0);
~Widget();

virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);

private:
Ui::Widget *ui;
QPoint z;
};

#endif // WIDGET_H

如果你觉得文章还不错,记得”点赞关注“

关注我的微信公众号【 加班猿 】可以获取更多内容

在这里插入图片描述


← Prev Qt实现自定义图标功能 | Qt笔记总结 Next →
打赏
支付宝 | Alipay
微信 | WeChat