zoukankan      html  css  js  c++  java
  • 在非gui线程使用QMessageBox

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

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

    特新介绍

    1.可以在任何线程调用

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

    注意:

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

    上源码

    申明:

    [cpp] view plaincopy
     
    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. };  

    定义:

    [cpp] view plaincopy
     
    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 plaincopy
     
    1. JasonQt_ShowInformationMessageBoxFromOtherThread::show("Title", "Message");  

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

    0
  • 相关阅读:
    Flask 5 模板1
    Flask 4 拓展
    Python学习札记(二十四) 函数式编程5 返回函数
    Python学习札记(二十三) 函数式编程4 sorted
    Docker:Err http://archive.ubuntu.com trusty InRelease & E: Unable to locate package [name] 问题
    解决 docker: Error response from daemon: ... : net/http: TLS handshake timeout.
    Ubuntu 安装Docker
    Flask 3 程序的基本结构2
    Flask 2 程序的基本结构1
    Flask 1 Introductory Chapter
  • 原文地址:https://www.cnblogs.com/findumars/p/5034524.html
Copyright © 2011-2022 走看看