【Qt】移動無邊框表單

來源:互聯網
上載者:User

標籤:

  分類: Qt2013-05-08 22:55 3027人閱讀 評論(7) 收藏 舉報

移動無邊框表單的代碼網上很多,其原理都是一樣的,但是是有問題的,我這裡只是對其修正一下

網上的代碼僅僅實現了兩個事件

[cpp] view plaincopy 
  1. void EditDialog::mousePressEvent(QMouseEvent *event)  
  2. {  
  3.     if (event->button() == Qt::LeftButton) {  
  4.         m_DragPosition = event->globalPos() - this->pos();  
  5.         event->accept();  
  6.     }  
  7. }  
  8.   
  9. void EditDialog::mouseMoveEvent(QMouseEvent *event)  
  10. {  
  11.     if (event->buttons() && Qt::LeftButton) {  
  12.         move(event->globalPos() - m_DragPosition);  
  13.         event->accept();  
  14.     }  
  15. }  

但是這樣就會有一個問題,就是當滑鼠在一個實現了mousePressEvent的類上點擊時(比如QPushButton)會被該類優先處理此事件

而不會將事件傳遞到表單的mousePressEvent中。繼續,當移動滑鼠到這個按鈕外時(假設點在了QPushButton上)會觸發表單的mouseMoveEvent

從而導致計算座標時發生錯誤,此時你就會看到表單閃了一下,變動了位置,滑鼠也沒有停在前面按下的按鈕之上。

解決辦法也很簡單,就是再多聲明一個bool變數來判斷,並實現mouseReleaseEvent即可

[cpp] view plaincopy 
  1. void EditDialog::mousePressEvent(QMouseEvent *event)  
  2. {  
  3.     if (event->button() == Qt::LeftButton) {  
  4.         m_Drag = true;  
  5.         m_DragPosition = event->globalPos() - this->pos();  
  6.         event->accept();  
  7.     }  
  8. }  
  9.   
  10. void EditDialog::mouseMoveEvent(QMouseEvent *event)  
  11. {  
  12.     if (m_Drag && (event->buttons() && Qt::LeftButton)) {  
  13.         move(event->globalPos() - m_DragPosition);  
  14.         event->accept();  
  15.     }  
  16. }  
  17.   
  18. void EditDialog::mouseReleaseEvent(QMouseEvent *)  
  19. {  
  20.     m_Drag = false;  
  21. }  


這樣,就完成了無邊框表單的拖動。可是,這樣做的效率並不高,因為滑鼠每次move時都會觸發事件,計算位置,移動視窗,重繪視窗……

當表單上有QWebView組件時,特別是網頁中有圖片,Flash時,你就會發現用上面的方案去移動表單時會非常不流暢。

 

如果不考慮跨平台,只針對Windows平台,那麼我建議用Windows下的標準方法,類比標題列移動訊息,既簡單又高效

[cpp] view plaincopy 
  1. void MainWindow::mousePressEvent(QMouseEvent *event)  
  2. {  
  3.     if (ReleaseCapture())  
  4.         SendMessage(HWND(this->winId()), WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);  
  5.     event->ignore();  
  6. }  

 這樣,在拖動表單時只會在鬆開滑鼠時才將表單移動過去,這樣就避免了第一種方法的低效率問題

【Qt】移動無邊框表單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.