Following the official documentation, I am trying to do this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QThread *thread = new QThread;
Worker *worker= new Worker();
worker->moveToThread(thread);
thread->start();
}
Workflow Designer:
Worker::Worker(QObject *parent) :
QObject(parent)
{
serial = new QSerialPort(this);
}
There is no compilation of errors, but when I execute it, it throws me:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0x11bd1148), parent thread is QThread(0x11bd2ef8), current thread is QThread(0x3e47b8)
Namely, this tells me that it serialhas the main thread as the parent, and not the thread that I created.
The same result, if I do not create the serial number in the constructor, but in the main process, which starts after we called thread->start():
Worker::Worker(QObject *parent) :
QObject(parent)
{
}
Worker::doWork()
{
if(!serial)
serial= new QSerialPort(this);
}
What am I missing?
Send the function as an example (slot):
void Worker::send(const QByteArray &data)
{
serial->write(data);
if( serial->waitForBytesWritten(TIMEOUT) )
qDebug() << "sent: " << data;
}
source
share