I am at the beginning of a POC task and get the exact code from this address: https://www.bogotobogo.com/Qt/Qt5_QTcpSocket_Signals_Slots.php

While the code works perfectly in Qt Creator, I get he error QObject: Cannot create children for a parent that is in a different thread when I try to run the same code in Visual Studio in the line socket = new QTcpSocket(this); My Visual Studio version is 2017, Qt version is 5.9.9. I use the same QT version on both QT Creator and Visual Studio.

I have checked related posts but all mention about creating a thread. I don't create a thread.

Here is the code: mytcpsocket.h

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QObject>
#include <QtNetwork/qtcpsocket.h>
#include <QDebug>

class MyTcpSocket : public QObject
{
    Q_OBJECT
public:
    explicit MyTcpSocket(QObject *parent = 0);

    void doConnect();

signals:

public slots:
    void connected();
    void disconnected();
    void bytesWritten(qint64 bytes);
    void readyRead();

private:
    QTcpSocket *socket;

};

#endif // MYTCPSOCKET_H

mytcpsocket.cpp

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QObject>
#include <QtNetwork/qtcpsocket.h>
#include <QDebug>

class MyTcpSocket : public QObject
{
    Q_OBJECT
public:
    explicit MyTcpSocket(QObject *parent = 0);

    void doConnect();

signals:

public slots:
    void connected();
    void disconnected();
    void bytesWritten(qint64 bytes);
    void readyRead();

private:
    QTcpSocket *socket;

};

#endif // MYTCPSOCKET_H

And the main.cpp

#include <QCoreApplication>
#include "mytcpsocket.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyTcpSocket s;
    s.doConnect();
    return a.exec();
}
1

There are 1 best solutions below

0
Ali Forouzan On

about Qobject these notes are important:

The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object (this) as the parent of an object created in the thread (since the QThread object itself was created in another thread).

Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.

You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.

read more in QObject Reentrancy