QT + How to call slot from custom C++ code running in a different thread

qt, qt4, signals-slots

Solution

In addition to stribika's answer, I often find it easier to use a signal/slot connection. You can specify that it should be a queued connection when you connect it, to avoid problems with the thread's signals being in the context of its owning object.

class mythread : public QThread
{
signals:
    void appendText( QString );
public:

    mythread(mywindow* win){this->w = win;};
    mywindow* w;
    void run()
    {
        emit ( appendText( "Hello" ) );
    };
};

int main(int argc, char *argv[])
{
    QApplication* a = new QApplication(argc, argv);
    mywindow* w = new mywindow();

    w->show();
    mythread* thr = new mythread(w);
    (void)connect( thr, SIGNAL( appendText( QString ) ),
                   w->ui.textEdit, SLOT( append( QString ) ),
                   Qt::QueuedConnection ); // <-- This option is important!
    thr->start();

    return a->exec();
}

Problem

I am new to QT and I am doing some learning. I would like to trigger a slot that modify a GUI widget from a C++ thread(Currently a Qthread). Unfortunatly I get a: ASSERTION failed at: Q_ASSERT(qApp && qApp->thread() == QThread::currentThread()); here is some code: (MAIN + Thread class) ``` class mythread : public QThread { public: mythread(mywindow* win){this->w = win;}; mywindow* w; void run() { w->ui.textEdit->append("Hello"); //<--ASSERT FAIL //I have also try to call a slots within mywindow which also fail. }; }; int main(int argc, char *argv[]) { QApplication* a = new QApplication(argc, argv); mywindow* w = new mywindow(); w->show(); mythread* thr = new mythread(w); thr->start(); return a->exec(); } ``` Window: ``` class mywindow : public QMainWindow { Q_OBJECT public: mywindow (QWidget *parent = 0, Qt::WFlags flags = 0); ~mywindow (); Ui::mywindow ui; private: public slots: void newLog(QString &log); }; ``` So I am curious on how to update the gui part by code in a different thread. Thanks for helping

Original source