我是靠谱客的博主 善良纸鹤,这篇文章主要介绍Qt无边框窗口拖拽和阴影的实现方法,现在分享给大家,希望可以做个参考。

无边框窗口的实现

只需要一行代码即可实现

复制代码
1
this->setWindowFlags(Qt::FramelessWindowHint);

代码及运行效果:

无边框窗口能拖拽实现

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

理一下 坐标的位置 情况:

左上角:屏幕的左上角

中间的窗口:程序的窗口

箭头:鼠标位置

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

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

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

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

复制代码
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(); //鼠标松开获取当前的坐标  }

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

源码:

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
#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

总结

到此这篇关于Qt无边框窗口拖拽和阴影的实现方法的文章就介绍到这了,更多相关Qt无边框窗口拖拽和阴影内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是善良纸鹤最近收集整理的关于Qt无边框窗口拖拽和阴影的实现方法的全部内容,更多相关Qt无边框窗口拖拽和阴影内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部