Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i show MessageBox in another thread Qt

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.

like image 906
Alexander Mashin Avatar asked Jun 02 '14 10:06

Alexander Mashin


1 Answers

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();
    }

};
like image 184
Dmitry Sazonov Avatar answered Oct 24 '22 18:10

Dmitry Sazonov