這兒用上了前面一文提到的函數findDesktopIconWnd()。
見: http://mypyg.blog.51cto.com/820446/263349
一、將Qt窗口嵌入到桌面中。
聲明一個最簡單的類:
class Dialog :
public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
}
函數實現:
Dialog::Dialog(QWidget *parent) : QDialog(parent)
{
//創建個LineEdit用來測試焦點
QLineEdit* le =
new QLineEdit(
this);
}
Dialog::~Dialog()
{
}
主函數:
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();
}
運行效果:
有個窗口嵌入了桌面。按win+D組合鍵可以看到此窗口在桌面上。
二、讓窗口全透明:
2.1最容易想到的就是setWindowOpacity()函數了。
w.setWindowOpacity(0.5),運行:結果杯具了,此函數完全無效,因為其父窗口特殊,這個函數內部使用的系統窗口標志不被支持。
2.2
w.setAttribute(Qt::WA_TranslucentBackground, true);
運行效果:
全透明ok。如果其父窗口為空的話,透明的地方會成為黑塊。
三、讓窗口半透明
3.1w.setAttribute(Qt::WA_TranslucentBackground, true) + 背景調色板
運行效果仍然是全透明,因為TranslucentBackground為true,根本不畫背景。
3.2單純的背景調色板:
QPalette pal = w.palette();
pal.setColor(QPalette::Background, QColor(100,100,100,50));
w.setPalette(pal);
w.setAutoFillBackground(
true);
運行效果出現了半透明:
但是還沒大功告成,不停點擊桌面,再點擊這個窗口,會發現這個窗口越來越不透明,直至完全不透明了。不知道是不是qt的bug。
ps:加一句 w.setAttribute(Qt::WA_OpaquePaintEvent,true); 窗口就能夠一直保持這個效果了。即這個方案可行。
pps:此方案在XP也是黑色底塊。
3.3轉戰paintEvent()
protected:
void paintEvent(QPaintEvent *);
void Dialog::paintEvent(QPaintEvent *e)
{
QPainter p(
this);
p.fillRect(rect(), QColor(0,0xff,0,30));
}
用一個帶有alpha值的顏色填充背景,運行效果發現顏色確實有alpha值,但是桌面的內容透不過來。
3.4setAttribute(Qt::WA_TranslucentBackground, true) + paintEvent()
運行效果:
得到了設想中的效果。
最終的主函數代碼:
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實現代碼:
Dialog::Dialog(QWidget *parent) : QWidget(parent)
{
//創建個LineEdit用來測試焦點
QLineEdit* le =
new QLineEdit(
this);
}
Dialog::~Dialog()
{
}
void Dialog::paintEvent(QPaintEvent *e)
{
QPainter p(
this);
p.fillRect(rect(), QColor(0,0xff,0,30));
}
PS:
經測試此代碼在XP運行不正常。窗口成為黑色背景塊。只能是顏色半透明了。
還有就是圖標會被蓋住。只能把w.setAttribute(Qt::WA_TranslucentBackground, true);注釋掉,有半透明顏色,無法看到桌面。
http://mypyg.blog.51cto.com/820446/263369
