Class Instances are created on the calling thread.
QTimer
inherits QObject
.
Each Thread on Qt
can have an event loop if it calls exec()
.
so you want to move QTimer
to an event loop on another thread.
so you should manually move it.
Therefore, delay their creation until after you move the object: -
class CommsHandlerIP : public QObject
{
Q_OBJECT
public slots:
void Initialise();
private:
void Run();
// c++ 11, initialising in headers...
QTimer* m_pTimer = NULL;
QTcpSocket* m_pSocket = NULL;
};
void CommsHandlerIP::Initialise()
{
m_pTimer = new QTimer(this);
m_pSocket = new QTcpSocket(this);
Run();
}
QThread m_commsThread;
m_pICommsHandler = new CommsHandlerIP();
// Note Qt 5 connect style
connect(&m_commsThread, &QThread::started, m_pICommsHandler, &CommsHandlerIP::Initialise);
m_pICommsHandler->moveToThread(&m_commsThread);
m_commsThread.start();
When the thread is started, the CommsHanderIP
Initialise function is called; this is where you should create and setup the QTcpSocket
and QTimer
objects before calling Run()
. As the CommsHandlerIP
is running in the new thread before creating those objects, they will also share the same thread affinity.