How do I use a QTcpSocket from a subclass of QThread?
Solved
General and Desktop
-
I am reading from a Tcp socket in a separate thread:
class ReadFromTcpThread : public QThread { Q_OBJECT public: ReadFromTcpThread(const std::string& tcpAddress, unsigned int port) : m_tcpAddress(tcpAddress), m_port(port) { }; void run() override; private slots: void connected(); void errorOccurred(QAbstractSocket::SocketError e_socketError); void processPendingBytes(); private: std::string m_tcpAddress; unsigned int m_port; QTcpSocket* m_tcpSocket = nullptr; QByteArray m_data; };
void ReadFromTcpThread::run() { m_tcpSocket = new QTcpSocket; m_tcpSocket->moveToThread(QThread::currentThread()); m_tcpSocket->connectToHost(m_tcpAddress.c_str(), m_port); connect(m_tcpSocket, &QAbstractSocket::connected, this, &ReadFromTcpThread::connected); connect(m_tcpSocket, &QAbstractSocket::errorOccurred, this, &ReadFromTcpThread::errorOccurred); connect(m_tcpSocket, &QTcpSocket::readyRead, this, &ReadFromTcpThread::processPendingBytes); exec(); // run event loop }
Is this correct code?
It seems to work. If I used theQThread
as the parent of the socket I got an error. Since the socket is created inside the run method I do not need tomoveToThread()
? -
@andyP said in How do I use a QTcpSocket from a subclass of QThread?:
Is this correct code?
No since all your slot are executed in the main thread because your ReadFromTcpThread lives in the main thread.
- don't use threads for QTcpSocket - it's not needed
- if you use a thread, use the worker approach to make sure all your stuff is done in your created thread.