最近我写项目的时候遇到一个奇怪的需求,要在工作线程内,根据某个情况弹出一个MessageBox
但是Qt提供的MessageBox只可以在gui线程(主线程)使用,于是我就对QMessageBox封装了一下,让其可以在非gui线程内被调用
特新介绍
1.可以在任何线程调用
2.show后和默认的MessageBox一样是阻塞的,MessageBox关闭后才会返回
注意:
1.我只封装了information,如果需要其他的,请做扩展
上源码
申明:
- #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);
- };
定义:
- 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
- 0