Qt无边框窗口拖拽和阴影的实现方法

无边框窗口的实现

只需要一行代码即可实现

this->setWindowFlags(Qt::FramelessWindowHint);

代码及运行效果:

无边框窗口能拖拽实现

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

理一下 坐标的位置 情况:

左上角:屏幕的左上角

中间的窗口:程序的窗口

箭头:鼠标位置

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

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

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

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

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

 #include "widget.h" #include <QApplication> ​ int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); ​ return a.exec(); }

widget.cpp

 #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

 #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无边框窗口拖拽和阴影的实现方法

相关文章:

你感兴趣的文章:

标签云: