How to configure QSerialPort on a separate thread?

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);

    //init connections

    thread->start();
}

Workflow Designer:

Worker::Worker(QObject *parent) :
    QObject(parent)
{
    serial = new QSerialPort(this);  //passing the parent, which should be the current thread      
}

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;
}
+4
source share
1 answer

In short, it’s nice to use the QtSerialPort module as follows.

QIODevice, GUI QSerialPort.

:

void QIODevice:: bytesWritten (qint64 bytes) [signal]

, . , . bytesWritten() ; waitForBytesWritten() , bytesWritten(), ( waitForBytesWritten() true).

...

void QIODevice:: readyRead() [signal]

, . , , , .

readyRead() ; waitForReadyRead() , readyRead(), ( waitForReadyRead() true).

, , QIODevice: readyRead(), ( , ). readyRead() .

, :

+5

Source: https://habr.com/ru/post/1539881/


All Articles