How can i show MessageBox in another thread Qt

c++, multithreading, qmessagebox, qt

Solution

What you are doing wrong?

You are trying to show widget in non-gui thread.

How to fix?

class TestClass: public QObject
{
    Q_OBJECT
    public slots:
        void something()
        {
            TestThread *thread = new TestThread();

            // Use Qt::BlockingQueuedConnection !!!
            connect( thread, SIGNAL( showMB() ), this, SLOT( showMessageBox() ), Qt::BlockingQueuedConnection ) ;

            thread->start();
        }
        void showMessageBox()
        {
            QMessageBox Msgbox;
            Msgbox.setText("Hello!");
            Msgbox.exec();
        }
};


class TestThread: public QThread
{
    Q_OBJECT
signals:
    void showMB();
protected:
    void run()
    {
        sleep(1);
        emit showMB();
    }

};

Problem

That's my code for this: ``` int main(int argc, char *argv[]) { QApplication a(argc, argv); testApp w; w.show(); TestClass *test = new TestClass; QObject::connect(w.ui.pushButton, SIGNAL(clicked()), test, SLOT(something())); return a.exec(); } ``` TestClass.h ``` class TestClass: public QObject { Q_OBJECT public slots: void something() { TestThread *thread = new TestThread; thread -> start(); } }; ``` TestThread.h ``` class TestThread: public QThread { Q_OBJECT protected: void run() { sleep(1000); QMessageBox Msgbox; Msgbox.setText("Hello!"); Msgbox.exec(); } }; ``` If i'm doing this, i see error widgets must be created in the gui thread What am I doing wrong? Please help me. I know that I cant change gui in another thread, but i dont know constuctions in qt for this.

Original source