在非gui線程使用QMessageBox

最近我寫項目的時候遇到一個奇怪的需求,要在工做線程內,根據某個狀況彈出一個MessageBoxoop

可是Qt提供的MessageBox只能夠在gui線程(主線程)使用,因而我就對QMessageBox封裝了一下,讓其能夠在非gui線程內被調用ui

 

特新介紹this

1.能夠在任何線程調用spa

2.show後和默認的MessageBox同樣是阻塞的,MessageBox關閉後纔會返回.net

 

注意:線程

1.我只封裝了information,若是須要其餘的,請作擴展orm

 

上源碼blog

申明:ip

 

[cpp]  view plain copy
 
  1. #include <QMessageBox>  
  2. #include <QEventLoop>  
  3.   
  4. class JasonQt_ShowInformationMessageBoxFromOtherThread: public QObject  
  5. {  
  6.     Q_OBJECT  
  7.   
  8. private:  
  9.     const QString m_title;  
  10.     const QString m_message;  
  11.   
  12. public:  
  13.     JasonQt_ShowInformationMessageBoxFromOtherThread(const QString &title, const QString &message);  
  14.   
  15.     static void show(const QString &title, const QString &message);  
  16.   
  17. private:  
  18.     void readyShow(void);  
  19.   
  20. private slots:  
  21.     void onShow(void);  
  22. };  

 

 

定義:get

 

[cpp]  view plain copy
 
  1. JasonQt_ShowInformationMessageBoxFromOtherThread::JasonQt_ShowInformationMessageBoxFromOtherThread(const QString &title, const QString &message):  
  2.     m_title(title),  
  3.     m_message(message)  
  4. { }  
  5.   
  6. void JasonQt_ShowInformationMessageBoxFromOtherThread::show(const QString &title, const QString &message)  
  7. {  
  8.     QEventLoop eventLoop;  
  9.     auto messageBox = new JasonQt_ShowInformationMessageBoxFromOtherThread(title, message);  
  10.     connect(messageBox, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));  
  11.     messageBox->readyShow();  
  12.     eventLoop.exec();  
  13. }  
  14.   
  15. void JasonQt_ShowInformationMessageBoxFromOtherThread::readyShow(void)  
  16. {  
  17.     this->moveToThread(qApp->thread());  
  18.     QTimer::singleShot(0, this, SLOT(onShow()));  
  19. }  
  20.   
  21. void JasonQt_ShowInformationMessageBoxFromOtherThread::onShow(void)  
  22. {  
  23.     QMessageBox::information(NULL, m_title, m_message);  
  24.     this->deleteLater();  
  25. }  

 

 

使用:

 

[cpp]  view plain copy
 
  1. JasonQt_ShowInformationMessageBoxFromOtherThread::show("Title", "Message");  

 

http://blog.csdn.net/wsj18808050/article/details/43020563

0
相關文章
相關標籤/搜索