Qt在子线程中使用MessageBox

2022-07-29,,

Qt在子线程调用窗体会报出如下错误。

解决方法如下:

头文件

#ifndef MSGBOX_H
#define MSGBOX_H

#include <QObject>
#include<QEventLoop>
#include<QMessageBox>
#include<QApplication>
#include<QTimer>
class msgBox:public QObject
{
    Q_OBJECT
public:
    explicit msgBox(QObject *parent = nullptr);
private:
    const QString title;
    const QString msg;
    int type;
    void readyShow(void);
public:
    msgBox(const QString &title, const QString &msg,const int type);
    static void show(const QString &title,const QString &msg,const int type);
public slots:
    void onShow();


};

#endif // MSGBOX_H

 cpp文件

#include "msgbox.h"

msgBox::msgBox(QObject *parent):QObject (parent)
{

}

void msgBox::readyShow()
{
    this->moveToThread(qApp->thread());
    QTimer::singleShot(0,this,SLOT(onShow()));
}

msgBox::msgBox(const QString &title, const QString &msg,const int type):title(title),msg(msg),type(type)
{

}

void msgBox::show(const QString &title, const QString &msg,const int type)
{
    QEventLoop eventLoop;
    auto messageBox = new msgBox(title,msg,type);
    connect(messageBox,SIGNAL(destroyed()),&eventLoop,SLOT(quit()));
    messageBox->readyShow();
    eventLoop.exec();
}

void msgBox::onShow()
{
    switch (type)
    {
    case 1:
        QMessageBox::information(NULL,title,msg,QString::fromLocal8Bit("ok"));
        break;
    case 2:
        QMessageBox::critical(NULL,title,msg,QString::fromLocal8Bit("ok"));
        break;
    case 3:
        QMessageBox::question(NULL,title,msg,QString::fromLocal8Bit("ok"));
        break;
    }


    this->deleteLater();
}

使用


msgBox::show("info","operaiton is ok",1);
msgBox::show("info","operaiton is ok",2);
msgBox::show("info","operaiton is ok",3);

本文地址:https://blog.csdn.net/weixin_41882459/article/details/108586077

《Qt在子线程中使用MessageBox.doc》

下载本文的Word格式文档,以方便收藏与打印。