Qt無邊框窗口拖拽和陰影


Qt無邊框窗口拖拽和陰影

 

作者:hackett
微信公眾號:加班猿

 

無邊框窗口的實現

只需要一行代碼即可實現

 this->setWindowFlags(Qt::FramelessWindowHint);

image-20201102191116019

代碼及運行效果:

image-20201102191340908

無邊框窗口能拖拽實現

先要去QWidget里面找到鼠標事件函數

image-20201102192216514

理一下坐標的位置情況:

左上角:屏幕的左上角

中間的窗口:程序的窗口

箭頭:鼠標位置

坐標位置滿足:x = y - z

image-20201102193018846

 

在Designer里面拖一個Widget出來叫shadowWidget

image-20201102195257871

shadowWidget的顏色為灰色,我們選個自己喜歡的背景色方便查看

image-20201102200730118

接下來我們要重寫鼠標事件函數才能讓拖拽功能生效

 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

 #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

如果你覺得文章還不錯,記得"點贊關注"

關注我的微信公眾號【 加班猿 】可以獲取更多內容

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM