Important: Please read the Qt Code of Conduct -

how signal and slots is working here

  • In code below,the slot(STOP()) is running in main thread.As per my knowledge if we use direct connection then and only then the slot will run into sender's thread.

    #if QT_VERSION>=0x050000
    #include <QtWidgets>
    #include <QtGui>
    class Thread : public QThread
    public slots:
        void stop()
            qDebug()<<"Thread::stop called from main thread: "<<currentThreadId();
            QMutexLocker locker(&m_mutex);
        QMutex m_mutex;
        bool m_stop;
        void run()
            qDebug()<<"From worker thread: "<<currentThreadId();
            while (1) {
                QMutexLocker locker(&m_mutex);
                if (m_stop) break;
    #include "main.moc"
    int main(int argc, char *argv[])
        QApplication a(argc, argv);
        qDebug()<<"From main thread: "<<QThread::currentThreadId();
        QPushButton btn("Stop Thread");
        Thread t;
        QObject::connect(&btn, SIGNAL(clicked()), &t, SLOT(stop()));
        QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));
        return a.exec();

    The output is more or less like

    From main thread: 0x13a8
    From worker thread: 0xab8
    Thread::stop called from main thread: 0x13a8

    i really not understand the reason behind stop() slot is running in mainthread.i checked it by putting directconnection ,i got the same result.stop() is running in main thread.what could be reason?

  • Hi,

    That's because QThread lives in the main thread. Only run() is executed in a different thread.

    edit: I think this post could help you

Log in to reply