Qt:在非gui线程使用QMessageBox

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


  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值