Following the official documentation I'm trying to do this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QThread *thread = new QThread;
Worker *worker= new Worker();
worker->moveToThread(thread);
//init connections
thread->start();
}
Worker constructor:
Worker::Worker(QObject *parent) :
QObject(parent)
{
serial = new QSerialPort(this); //passing the parent, which should be the current thread
}
No compiling errors but when I execute it throws me this:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0x11bd1148), parent's thread is QThread(0x11bd2ef8), current thread is QThread(0x3e47b8)
Namely, it's telling me that serial
has as a parent the main thread and not the thread that I have created.
The same result if I don't instantiate serial in the constructor but in the main process, which is triggered after we've called thread->start()
:
Worker::Worker(QObject *parent) :
QObject(parent)
{
}
Worker::doWork()
{
if(!serial)
serial= new QSerialPort(this);
//...
}
What am I missing?
Send function as an example (a slot):
void Worker::send(const QByteArray &data)
{
serial->write(data);
if( serial->waitForBytesWritten(TIMEOUT) )
qDebug() << "sent: " << data;
}