Qt 無邊框、透明、可移動、的個性窗體案例詳解

pamxy發表於2013-04-28

轉自:http://blog.csdn.net/yiyaaixuexi/article/details/6362865

    

很多朋友都問透明的效果怎麼做,為什麼自己做的無邊框窗體不可移動,一個個回答的很累,乾脆寫出來分享下好了.

  1. int main(int argc, char *argv[]){  
  2.   
  3.    QApplication::setStyle("cleanlooks");  
  4.   
  5.    QApplication a(argc, argv);  
  6.    login w;  
  7.    w.setWindowTitle("ClientLogin");  
  8.   
  9.   
  10.    w.setWindowOpacity(1);  
  11.    w.setWindowFlags(Qt::FramelessWindowHint);  
  12.    w.setAttribute(Qt::WA_TranslucentBackground);  
  13.    w.show();  
  14.    w.move(200,100);  
  15.    return a.exec();  


關鍵的語句,就是其中的:

  1. w.setWindowOpacity(1);      
  2. w.setWindowFlags(Qt::FramelessWindowHint);      
  3. w.setAttribute(Qt::WA_TranslucentBackground);  

這些語句,不知道什麼意思就摁下F1,或者直接查閱幫助文件……

對窗體無邊框的設定要寫在main裡面,這樣所有派生的子視窗,QDialog,QWidget都可繼承,  很好規劃和管理,方便統一美化設計。

以工程中一個聊天視窗為例,先用PS製作一個窗體的背景圖片,注意存為png格式,這是透明的關鍵。不會使PS,可以找些PNG資源圖片。   我的PNG透明背景圖為:

 

 4

將它新增到你的資源包中,然後設定為窗體的背景。     

下圖是我的工程,其中的場景設定其實也是更換組建的背景圖片嘍~~   的

     

這個你就可以預覽到透明的無邊框窗體了,但是還有一個重要的問題,視窗竟然無法移動。
這也是無邊框導致的……具體原因我不細說,搜一下很清晰,我只說解決方案。
在每個子視窗中,都新增:

  1. void yourwindow::mousePressEvent(QMouseEvent *event){                                                                                                          
  2.         this->windowPos = this->pos();   
  3.         this->mousePos = event->globalPos();  
  4.         this->dPos = mousePos - windowPos;  
  5. }  
  6. void yourwindow::mouseMoveEvent(QMouseEvent *event){   
  7.         this->move(event->globalPos() - this->dPos);  
  8. }  


這樣就大功告成了,執行一下看看效果,綠森林是俺滴桌面,可以忽略之。

 

到底

 歡迎交流


相關文章