c/c++语言开发共享Qt在子线程中使用MessageBox

Qt在子线程调用窗体会报出如下错误。解决方法如下:头文件#ifndef MSGBOX_H#define MSGBOX_H#include <QObject>#include<QEventLoop>#include<QMessageBox>#include<QApplication>#include<QTimer>class 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

c/c++开发分享Qt在子线程中使用MessageBox地址:https://blog.csdn.net/weixin_41882459/article/details/108586077

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/597564.html

(0)
上一篇 2021年5月8日
下一篇 2021年5月8日

精彩推荐