Qt無邊框窗口拖拽和陰影的實現(xiàn)方法
無邊框窗口的實現(xiàn)
只需要一行代碼即可實現(xiàn)
this->setWindowFlags(Qt::FramelessWindowHint);

代碼及運行效果:

無邊框窗口能拖拽實現(xiàn)
先要去QWidget里面找到 鼠標(biāo)事件 函數(shù)

理一下 坐標(biāo)的位置 情況:
左上角:屏幕的左上角
中間的窗口:程序的窗口
箭頭:鼠標(biāo)位置
坐標(biāo)位置滿足: x = y - z

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

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

接下來我們要重寫鼠標(biāo)事件函數(shù)才能讓拖拽功能生效
void Widget::mouseMoveEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠標(biāo)相當(dāng)于桌面左上角的位置,鼠標(biāo)全局位置
QPoint x = y - this->z;
this->move(x);
}
void Widget::mousePressEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠標(biāo)相當(dāng)于桌面左上角的位置,鼠標(biāo)全局位置
QPoint x = this->geometry().topLeft();//窗口左上角位于桌面左上角的位置,窗口位置
this->z = y - x; //定值,不變
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
this->z = QPoint(); //鼠標(biāo)松開獲取當(dāng)前的坐標(biāo)
}
最終效果變?yōu)槭髽?biāo)可拖動的窗口:

源碼:
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); //父窗口設(shè)置透明,只留下子窗口
}
Widget::~Widget()
{
delete ui;
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠標(biāo)相當(dāng)于桌面左上角的位置,鼠標(biāo)全局位置
QPoint x = y - this->z;
this->move(x);
}
void Widget::mousePressEvent(QMouseEvent *event)
{
QPoint y = event->globalPos();//鼠標(biāo)相當(dāng)于桌面左上角的位置,鼠標(biāo)全局位置
QPoint x = this->geometry().topLeft();//窗口左上角位于桌面左上角的位置,窗口位置
this->z = y - x; //定值,不變
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
this->z = QPoint(); //鼠標(biāo)松開獲取當(dāng)前的坐標(biāo)
}
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
總結(jié)
到此這篇關(guān)于Qt無邊框窗口拖拽和陰影的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)Qt無邊框窗口拖拽和陰影內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ 使用CRC32檢測內(nèi)存映像完整性的實現(xiàn)步驟
當(dāng)我們使用動態(tài)補丁的時候,那么內(nèi)存中同樣不存在校驗效果,也就無法抵御對方動態(tài)修改機器碼了,為了防止解密者直接對內(nèi)存打補丁,我們需要在硬盤校驗的基礎(chǔ)上,增加內(nèi)存校驗,防止動態(tài)補丁的運用。2021-06-06
typedef_struct與struct之間的區(qū)別
本篇文章主要是對typedef struct與struct之間的區(qū)別進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12

