C++ 线程关联:无法为位于不同线程中的父级创建子级
我看到了一个,但我觉得我正在实现正确的模式,但我仍然无法完成它 嗯,我有一个Gui来启动和停止从串行端口的数据采集,并显示必要的通信消息。为了保持Gui的响应性,我将工作线程移动到一个线程。根据:和,我尝试实现线程关联。当我点击开始按钮时,我收到C++ 线程关联:无法为位于不同线程中的父级创建子级,c++,qthread,worker,qobject,affinity,C++,Qthread,Worker,Qobject,Affinity,我看到了一个,但我觉得我正在实现正确的模式,但我仍然无法完成它 嗯,我有一个Gui来启动和停止从串行端口的数据采集,并显示必要的通信消息。为了保持Gui的响应性,我将工作线程移动到一个线程。根据:和,我尝试实现线程关联。当我点击开始按钮时,我收到 QWinEventNotifier: event notifiers cannot be enabled from another thread QWinEventNotifier: event notifiers cannot be enabled
QWinEventNotifier: event notifiers cannot be enabled from another thread
QWinEventNotifier: event notifiers cannot be enabled from another thread
QWinEventNotifier: event notifiers cannot be enabled from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0x142cd390), parent's thread is QThread(0x1259b070), current thread is QThread(0x142db1f0)
我错过了什么?以下是与我的问题相关的部分代码:
工人头
谢谢你的回答,我解决了我的问题。我在ComPort的构造函数中创建了一个串行端口,它在主线程中被调用。当cPort对象移动到cThread时,QSerialPort仍然将其线程关联设置为原始线程。解决方案是在ComPort::setupPort中创建QSerialPort
#ifndef COMPORT_H
#define COMPORT_H
#include <QObject>
#include <QDebug>
#include <QSerialPort>
class QTimer;
class ComPort : public QObject
{
Q_OBJECT
public:
explicit ComPort(const QString &portName, QObject* parent = 0);
~ComPort();
private:
QSerialPort* port;
QString portMsg;
QByteArray responseData;
signals:
void finished();
private slots:
void onReadyRead();
void setupPort();
};
#endif // COMPORT_H
#include "comport.h"
ComPort::ComPort(const QString &portName, QObject *parent)
:QObject(parent)
{
this->port = new QSerialPort(portName);
}
ComPort::~ComPort()
{
port->close();
delete port;
}
void ComPort::setupPort()
{
port->setBaudRate(QSerialPort::Baud19200);
port->setDataBits(QSerialPort::Data8);
port->setFlowControl(QSerialPort::NoFlowControl);
port->setParity(QSerialPort::NoParity);
port->setStopBits(QSerialPort::OneStop);
connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
*SOME CODE HERE*
}
void ComPort::onReadyRead()
{
QByteArray bytes = port->readAll() ;
qDebug() << "bytes:" << bytes <<"\n";
responseData.append(bytes);
}
#include "gui.h"
#include "ui_gui.h"
gui::gui(QWidget *parent) :
QDialog(parent),
ui(new Ui::gui)
{
ui->setupUi(this);
connect(ui->startButton, SIGNAL(clicked()), this, SLOT(OnstartButtonClicked()));
}
gui::~gui()
{
delete ui;
}
void gui::OnstartButtonClicked()
{
QThread* cThread = new QThread;
ComPort* cPort = new ComPort(QString("COM4"));
cPort->moveToThread(cThread);
connect(cPort, SIGNAL(finished()), cThread, SLOT(quit()));
connect(cPort, SIGNAL(finished()), cPort, SLOT(deleteLater()));
connect(cThread, SIGNAL(finished()), cThread, SLOT(deleteLater()));
connect(cThread, SIGNAL(started()), cPort, SLOT(setupPort()));
cThread->start();
}