在非gui线程使用QMessageBox

时间:2023-03-08 20:41:59

最近我写项目的时候遇到一个奇怪的需求,要在工作线程内,根据某个情况弹出一个MessageBox

但是Qt提供的MessageBox只可以在gui线程(主线程)使用,于是我就对QMessageBox封装了一下,让其可以在非gui线程内被调用

特新介绍

1.可以在任何线程调用

2.show后和默认的MessageBox一样是阻塞的,MessageBox关闭后才会返回

注意:

1.我只封装了information,如果需要其他的,请做扩展

上源码

申明:

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

定义:

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

使用:

  1. JasonQt_ShowInformationMessageBoxFromOtherThread::show("Title", "Message");

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

0