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();
}
about Qobject these notes are important:
read more in QObject Reentrancy