最近我写项目的时候遇到一个奇怪的需求,要在工做线程内,根据某个状况弹出一个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