欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Qt在子线程中使用MessageBox

程序员文章站 2022-04-21 10:11:35
Qt在子线程调用窗体会报出如下错误。解决方法如下:头文件#ifndef MSGBOX_H#define MSGBOX_H#include #include#include#include#includeclass msgBox:public QObject{ Q_OBJECTpublic:...

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

Qt在子线程中使用MessageBox

解决方法如下:

头文件

#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);

Qt在子线程中使用MessageBoxQt在子线程中使用MessageBoxQt在子线程中使用MessageBox

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

相关标签: Qt