Connecting QThreadStorage local data signal to one slot in the same QThread
-
Hello everyone, this is my first post, so take this opportunity to greet the entire community.
My problem is as follows:
I am developing a simple TCP asynchronous chat application in Qt (client and server). Client and Server must interchange messages without blockings.
I have the following classes:
#ifndef CLIENTTHREAD_H
#define CLIENTTHREAD_H#include <QtCore>
#include <QtNetwork>
#include <QtGui>class ClientThread : public QThread
{
Q_OBJECTpublic:
ClientThread(QObject *parent);
void run(void);
~ClientThread(void);public slots:
void slot_connect(QString ip, quint16 port); //slot connected to signal emitted by GUI object QMainWindow
void slot_connectionOk(void);private:
QThreadStorage<QTcpSocket *> tcpSocket; //Having one local and independent QTcpSocket for each QThread
};#endif@
And the Definition of ClientThread class
#include "ClientThread.h"
ClientThread::ClienteThread(QObject *parent)
:QThread(parent)
{
}void ClientThread::slot_connect(QString ip, quint16 port)
{
this->tcpSocket.localData()->connectToHost(ip, port);
}void ClientThread::slot_connectionOk(void)
{
emit logMessage("Connection OK."); //This signal is connected to the QTcpSocket local data
}void ClienteThread::run(void)
{
if(this->tcpSocket.hasLocalData())
{
this->tcpSocket.localData()->abort();
}else
{
this->tcpSocket.setLocalData(new QTcpSocket());
connect(this->tcpSocket.localData(),SIGNAL(connected(void)),this,SLOT(slot_connectionOk(void)));
}
this->exec();
}ClientThread::~ClientThread(void)
{
}@In the constructor of the QChat QMainWindow class:
@// Q_OBJECT is declared in QChat.h
#include "QChat.h"
QChat::QChat(QWidget *parent, Qt::WFlags flags)
:QMainWindow(parent, flags),
thread(0)
{
ui.setupUi(this);//...
if(this->thread == 0)
{
this->thread = new ClientThread(this);connect(this->thread, SIGNAL(finished()), this->thread, SLOT(deleteLater()));
connect(this, SIGNAL(connectHost(QString,quint16)), this->thread, SLOT(slot_connect(QString,quint16)));
connect(this->thread, SIGNAL(logMessage(QString)), this, SLOT(slot_includeLog(QString)));this->thread->start();
}
//...
}//Declared as public slot in header file
void QChat::slot_includeLog(QString message) {ui.TX_Log->append(message);
}
//Declared as public slot in header file
void QChat::another_slot(void)
{
emit connectHost(ui.TX_Host->text(),ui.TX_Port->text().toUShort()); //this signal is declared as signal in header file
}@When connectHost is emitted, the slot slot_connect take the control, but the new signal that must be emitted by the local data in QThreadStorage<QTcpSocket *>, when the connection to host has been established (connected() signal), never is received by the slot slot_connectionOk(void).
What is the problem?
Thanks.