Qt實(shí)現(xiàn)半透明窗口 嵌入桌面
本文介紹的是Qt實(shí)現(xiàn)半透明窗口 嵌入桌面,窗口的一個(gè)特效,主要是有alpha值的顏色填充背景,最終的dialog實(shí)現(xiàn)看內(nèi)容。
一、將Qt窗口嵌入到桌面中。
聲明一個(gè)最簡(jiǎn)單的類(lèi):
- class Dialog : public QDialog
- {
- Q_OBJECT
- public :
- Dialog(QWidget *parent = 0);
- ~Dialog();
- }
函數(shù)實(shí)現(xiàn):
- Dialog::Dialog(QWidget *parent) : QDialog(parent)
- {
- //創(chuàng)建個(gè)LineEdit用來(lái)測(cè)試焦點(diǎn)
- QLineEdit* le = new QLineEdit(this );
- }
- ialog::~Dialog()
- {
- }
主函數(shù):
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Dialog w;
- HWND desktopHwnd = findDesktopIconWnd();
- if (desktopHwnd) SetParent(w.winId(), desktopHwnd);
- w.show();
- return a.exec();
- }
運(yùn)行效果:
有個(gè)窗口嵌入了桌面。按win+D組合鍵可以看到此窗口在桌面上。
二、讓窗口全透明:
2、最容易想到的就是setWindowOpacity()函數(shù)了。
w.setWindowOpacity(0.5),運(yùn)行:結(jié)果杯具了,此函數(shù)完全無(wú)效,因?yàn)槠涓复翱谔厥?,這個(gè)函數(shù)內(nèi)部使用的系統(tǒng)窗口標(biāo)志不被支持。
2、
w.setAttribute(Qt::WA_TranslucentBackground, true);
運(yùn)行效果:
全透明ok。如果其父窗口為空的話,透明的地方會(huì)成為黑塊。
三、讓窗口半透明
1、w.setAttribute(Qt::WA_TranslucentBackground, true) + 背景調(diào)色板
運(yùn)行效果仍然是全透明,因?yàn)門(mén)ranslucentBackground為true,根本不畫(huà)背景。
2、單純的背景調(diào)色板:
- QPalette pal = w.palette();
- pal.setColor(QPalette::Background, QColor(100,100,100,50));
- w.setPalette(pal);
- w.setAutoFillBackground(true );
運(yùn)行效果出現(xiàn)了半透明:
但是還沒(méi)大功告成,不停點(diǎn)擊桌面,再點(diǎn)擊這個(gè)窗口,會(huì)發(fā)現(xiàn)這個(gè)窗口越來(lái)越不透明,直至完全不透明了。不知道是不是qt的bug。
ps:加一句 w.setAttribute(Qt::WA_OpaquePaintEvent,true); 窗口就能夠一直保持這個(gè)效果了。即這個(gè)方案可行。
pps:此方案在XP也是黑色底塊。
3、轉(zhuǎn)戰(zhàn)paintEvent()
- protected :
- void paintEvent(QPaintEvent *);
- void Dialog::paintEvent(QPaintEvent *e)
- {
- QPainter p(this );
- p.fillRect(rect(), QColor(0,0xff,0,30));
- }
用一個(gè)帶有alpha值的顏色填充背景,運(yùn)行效果發(fā)現(xiàn)顏色確實(shí)有alpha值,但是桌面的內(nèi)容透不過(guò)來(lái)。
4、setAttribute(Qt::WA_TranslucentBackground, true) + paintEvent()
運(yùn)行效果:
最終的主函數(shù)代碼:
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Dialog w;
- HWND desktopHwnd = findDesktopIconWnd();
- if (desktopHwnd) SetParent(w.winId(), desktopHwnd);
- w.setAttribute(Qt::WA_TranslucentBackground, true );
- w.show();
- return a.exec();
- }
最終的dialog實(shí)現(xiàn)代碼:
- Dialog::Dialog(QWidget *parent) : QWidget(parent)
- {
- //創(chuàng)建個(gè)LineEdit用來(lái)測(cè)試焦點(diǎn)
- QLineEdit* le = new QLineEdit(this );
- }
- Dialog::~Dialog()
- {
- }
- void Dialog::paintEvent(QPaintEvent *e)
- {
- QPainter p(this );
- p.fillRect(rect(), QColor(0,0xff,0,30));
- }
經(jīng)測(cè)試此代碼在XP運(yùn)行不正常。窗口成為黑色背景塊。只能是顏色半透明了。還有就是圖標(biāo)會(huì)被蓋住。只能把w.setAttribute(Qt::WA_TranslucentBackground, true );注釋掉,有半透明顏色,無(wú)法看到桌面。
小結(jié):Qt實(shí)現(xiàn)半透明窗口 嵌入桌面的內(nèi)容介紹完了,其實(shí)這個(gè)實(shí)例也挺簡(jiǎn)單的,相信也能實(shí)現(xiàn)。最后希望本文對(duì)你有所幫助吧。