Pop up a QMessageBox from a QThread



  • I'm in a thread and I would like to pop up a QMessageBox displaying a Text when a QPushButton is clicked, how do I do it?
    Here's my code...

    myThread.h

    @#ifndef MYTHREAD_H
    #define MYTHREAD_H

    #include <QWidget>

    namespace Ui {
    class myThread;
    }

    class myThread: public QWidget
    {
    Q_OBJECT

    public:
    explicit myThread(QWidget *parent = 0);
    ~myThread();

    private slots:
    void on_pushButton_clicked();
    void workThread();
    };

    #endif // MYTHREAD_H@

    myThread.cpp

    @#include "myThread.h"
    #include "WorkThread.h"
    #include <QThread>

    myThread::myThread(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::myThread)
    {
    ui->setupUi(this);
    }

    myThread::~myThread()
    {
    delete ui;
    }

    void myThread::on_pushButton_clicked()
    {
    workThread();
    }

    void myThread::workThread()
    {
    WorkThread *worker = new WorkThread(this);
    QThread *workerThread = new QThread(this);

    connect(workerThread, &QThread::started, worker, &WorkThread::doWork);
    worker->moveToThread(workerThread);
    
    workerThread->start();
    

    }@

    WorkThread.h

    @#ifndef WORKTHREAD_H
    #define WORKTHREAD_H

    #include <QObject>

    class WorkThread : public QObject
    {
    Q_OBJECT
    public:
    explicit WorkThread(QWidget *parentWidget, QObject *parent = 0);

    public slots:
    void doWork();

    private:
    QWidget *parentWidget;
    };

    #endif // WORKTHREAD_H@

    WorkThread.cpp

    @#include "WorkThread.h"
    #include <QMessageBox>

    WorkThread::WorkThread(QWidget *parentWidget, QObject *parent) :
    QObject(parent)
    {
    }

    void WorkThread::doWork()
    {
    QMessageBox *mBox = new QMessageBox(parentWidget);
    mBox->setText("This is my Text");
    }@

    Here my application gets crashed which says that widgets must be created in the GUI Thread? Please Suggest.


  • Lifetime Qt Champion

    Hi,

    You can't create widgets in any other thread than the main thread (the one from app.exec()) If you want to popup a message box based on something happening in a thread, you must emit a signal from that thread back to e.g. your main window and use your message box there


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.