Qt 無邊框、透明、可移動個性窗口

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

  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();  
 int main(int argc, char *argv[]){

    QApplication::setStyle("cleanlooks");

    QApplication a(argc, argv);
    login w;
    w.setWindowTitle("ClientLogin");


    w.setWindowOpacity(1);
    w.setWindowFlags(Qt::FramelessWindowHint);
    w.setAttribute(Qt::WA_TranslucentBackground);
    w.show();
    w.move(200,100);
    return a.exec();
}


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

  1. w.setWindowOpacity(1);      
  2. w.setWindowFlags(Qt::FramelessWindowHint);      
  3. w.setAttribute(Qt::WA_TranslucentBackground);  
w.setWindowOpacity(1);    
w.setWindowFlags(Qt::FramelessWindowHint);    
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. }  
void yourwindow::mousePressEvent(QMouseEvent *event){                                                                                                        
        this->windowPos = this->pos(); 
        this->mousePos = event->globalPos();
        this->dPos = mousePos - windowPos;
}
void yourwindow::mouseMoveEvent(QMouseEvent *event){ 
        this->move(event->globalPos() - this->dPos);
}


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

 

到底

 歡迎交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章