Qt透明無邊框窗口的實現(xiàn)示例
最近在封裝一些類的時候,打算做一個窗口框架,能實現(xiàn)拖動、無邊框、透明基本樣式等功能
0x00 如何透明窗口?
第一步:開啟窗口的透明層。
setWindowFlags(Qt::FramelessWindowHint); /* 注意:如果單純開啟窗口透明層效果,在Windows系統(tǒng)中必須設(shè)置, 其他系統(tǒng)可忽略。 */ setAttribute(Qt::WA_TranslucentBackground);
第二步: 重寫paintEvent事件并使用QPainter畫透明層。
void paintEvent(QPaintEvent *) { QPainter painter(this); /* 0x20為透明層顏色,可自定義設(shè)置為0x0到0xff */ painter.fillRect(this->rect(), QColor(0, 0, 0, 0x20)); }
0x01 如何無邊框窗口?
設(shè)置setWindowFlags(Qt::FramelessWindowHint);
即可無邊框窗口,但無法移動和改變大小。
0x02 如何拖拽窗口?
由于系統(tǒng)窗口被設(shè)置為Qt::FramelessWindowHint
會導(dǎo)致窗口不能被拖動。通過捕獲鼠標(biāo)移動事件從而實現(xiàn)窗口移動。
void mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { /* 捕獲按下時坐標(biāo) */ m_startPoint = frameGeometry().topLeft() - event->globalPos(); } } void mouseMoveEvent(QMouseEvent *event) { /* 移動窗口 */ this->move(event->globalPos() + m_startPoint); }
0x03 完整代碼
#include <QWidget> #include <QVBoxLayout> #include <QPushButton> #include <QPainter> #include <QMouseEvent> class TransparentWidget : public QWidget { Q_OBJECT public: TransparentWidget(QWidget *parent = 0) : QWidget(parent) { setWindowTitle(QString::fromLocal8Bit("透明無邊框窗口")); setFixedSize(480, 320); setWindowFlags(Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground); QPushButton *button = new QPushButton("Hello world!", this); button->setGeometry(5, 5, 80, 40); } void paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(this->rect(), QColor(0, 0, 0, 0x20)); /* 設(shè)置透明顏色 */ } void mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_startPoint = frameGeometry().topLeft() - event->globalPos(); } } void mouseMoveEvent(QMouseEvent *event) { this->move(event->globalPos() + m_startPoint); } private: QPoint m_startPoint; };
0x04 源碼地址
https://github.com/aeagean/QtCustomWidget
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C語言SetConsoleCursorInfo函數(shù)使用方法
這篇文章介紹了C語言SetConsoleCursorInfo函數(shù)的使用方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12c++基礎(chǔ)語法:構(gòu)造函數(shù)初始化列表
構(gòu)造函數(shù)需要初始化的數(shù)據(jù)成員,不論是否顯示的出現(xiàn)在構(gòu)造函數(shù)的成員初始化列表中,都會在該處完成初始化,并且初始化的順序和其在聲明時的順序是一致的,與列表的先后順序無關(guān)2013-09-09