说明
在Qt官方文档中提到,QSerialPort是不不支持跨线程调用的(Ps:在Qt中大部分是都不支持跨线程的)
可以通过Thread::moveToThread来实现定义和使用在同一线程。
部分代码
主线程中定义串口类
QThread *thread1 =new QThread;
QSharedPointer<serialportiml> impl = serialportiml::CreateSerialPortIml(cfg);
QObject::connect(thread1, &QThread::started, impl.get(), &serialportiml::Init);
QObject::connect(impl.get(), &serialportiml::destroyed, thread1, &QThread::quit);
QObject::connect(thread1, &QThread::finished, thread1, &QThread::deleteLater);
impl->moveToThread(thread1);
thread1->start();
串口的初始化在serialportiml::Init()中实现
void serialportiml::Init()
{
m_sptrSerialport = serialport::CreateSerialPort(m_setting);
m_sptrSerialport->Open();
}
QSharedPointer<serialport> serialport::CreateSerialPort(const QSettings& setting)
{
QSharedPointer<serialport> sptr = QSharedPointer<serialport>(new serialport());
sptr->Init(setting);
return sptr;
}
void serialport::Init(const QSettings& settings)
{
m_ptrSerialPort = new QSerialPort(this);
m_ptrSerialPort->setPortName(/*"COM8"*/settings.value("ladserport/portname","COM8").toString());/*settings.value("ladserport/portname","COM4").toString()*/
m_ptrSerialPort->setBaudRate(settings.value("ladserport/baudrate",921600).toInt()/*921600*/);
m_ptrSerialPort->setParity(QSerialPort::NoParity);
m_ptrSerialPort->setDataBits(QSerialPort::Data8);
m_ptrSerialPort->setStopBits(QSerialPort::OneStop);
}
通过impl->moveToThread(thread1);将impl对象放到thread1线程中执行。实现串口的QSerialPort类的定义和使用都在thread1中。