date:
updated:
Qt无边框窗口拖拽和阴影

作者:hackett
微信公众号:加班猿
无边框窗口的实现
只需要一行代码即可实现
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 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
|
如果你觉得文章还不错,记得”点赞关注“
关注我的微信公众号【 加班猿 】可以获取更多内容
