Important: Please read the Qt Code of Conduct -

QThread, signals and slots

  • Hi,
    I have a doubt regarding qThread.
    @void Worker::run()
    qWarning()<<"Thread Started";

    tcpServerConnection=new QTcpSocket();
    qWarning()<<"SOCKET ID"<<socketDescriptor;
           qWarning()<<"ERROR IN SOCKETDESCRIPTOR ";
                // something's wrong, we just emit a signal
           emit error(tcpServerConnection->error());
    connect(tcpServerConnection, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection);
    connect(tcpServerConnection, SIGNAL(disconnected()), this, SLOT(disconnected()));
    qDebug() << socketDescriptor << " Client connected";
    qWarning()<<"SOCKET DESCRIPTOR in worker"<< tcpServerConnection->socketDescriptor();



    this is the code of a QThread::run().
    I need to know in these connect statements the slots are executed, is these slots are executing in threads context or with the main thread?

  • Qt Champions 2017

    main thread context as worker object is owned by main thread. This is typical of signal and slot across thread.

  • Moderators


    If you subclass a QThread, do not add new slots to your subclass. This causes lots of problems and is considered bad practice. The "QThread documentation": says,

    "It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread."

    I recommend using the worker-object approach with moveToThread(). See the first example in the QThread documentation.

  • Btw., two excellent articles on this are: "You're doing it wrong": and "Threading without the headache": .

Log in to reply