按照官方文档,我正在尝试这样做:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QThread *thread = new QThread;
Worker *worker= new Worker();
worker->moveToThread(thread);
//init connections
thread->start();
}
工人构造函数:
Worker::Worker(QObject *parent) :
QObject(parent)
{
serial = new QSerialPort(this); //passing the parent, which should be the current thread
}
没有编译错误,但是当我执行它时会抛出这个:
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)
也就是说,它告诉我serial
主线程而不是我创建的线程作为父线程。
如果我不在构造函数中而是在主进程中实例化序列,结果相同,这在我们调用后触发thread->start()
:
Worker::Worker(QObject *parent) :
QObject(parent)
{
}
Worker::doWork()
{
if(!serial)
serial= new QSerialPort(this);
//...
}
我错过了什么?
以发送函数为例(一个槽):
void Worker::send(const QByteArray &data)
{
serial->write(data);
if( serial->waitForBytesWritten(TIMEOUT) )
qDebug() << "sent: " << data;
}