最近我寫項目的時候遇到一個奇怪的需求,要在工做線程內,根據某個狀況彈出一個MessageBoxoop
可是Qt提供的MessageBox只能夠在gui線程(主線程)使用,因而我就對QMessageBox封裝了一下,讓其能夠在非gui線程內被調用ui
特新介紹this
1.能夠在任何線程調用spa
2.show後和默認的MessageBox同樣是阻塞的,MessageBox關閉後纔會返回.net
注意:線程
1.我只封裝了information,若是須要其餘的,請作擴展orm
上源碼blog
申明:ip
- #include <QMessageBox>
- #include <QEventLoop>
-
- class JasonQt_ShowInformationMessageBoxFromOtherThread: public QObject
- {
- Q_OBJECT
-
- private:
- const QString m_title;
- const QString m_message;
-
- public:
- JasonQt_ShowInformationMessageBoxFromOtherThread(const QString &title, const QString &message);
-
- static void show(const QString &title, const QString &message);
-
- private:
- void readyShow(void);
-
- private slots:
- void onShow(void);
- };
定義:get
- JasonQt_ShowInformationMessageBoxFromOtherThread::JasonQt_ShowInformationMessageBoxFromOtherThread(const QString &title, const QString &message):
- m_title(title),
- m_message(message)
- { }
-
- void JasonQt_ShowInformationMessageBoxFromOtherThread::show(const QString &title, const QString &message)
- {
- QEventLoop eventLoop;
- auto messageBox = new JasonQt_ShowInformationMessageBoxFromOtherThread(title, message);
- connect(messageBox, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));
- messageBox->readyShow();
- eventLoop.exec();
- }
-
- void JasonQt_ShowInformationMessageBoxFromOtherThread::readyShow(void)
- {
- this->moveToThread(qApp->thread());
- QTimer::singleShot(0, this, SLOT(onShow()));
- }
-
- void JasonQt_ShowInformationMessageBoxFromOtherThread::onShow(void)
- {
- QMessageBox::information(NULL, m_title, m_message);
- this->deleteLater();
- }
使用:
- JasonQt_ShowInformationMessageBoxFromOtherThread::show("Title", "Message");
http://blog.csdn.net/wsj18808050/article/details/43020563