编写一段Qt6 多线程接收串口代码
时间: 2023-03-13 22:13:04 浏览: 178
下面是一段示例 Qt6 多线程接收串口代码:#include <QThread>
#include <QDebug>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>class SerialThread : public QThread
{
Q_OBJECT
public:
SerialThread(QObject *parent = nullptr);
~SerialThread();
void run();signals:
void dataReady(const QByteArray &data);private:
QSerialPort *serial;
};SerialThread::SerialThread(QObject *parent)
: QThread(parent)
{
serial = new QSerialPort(this);
connect(serial, &QSerialPort::readyRead, this, &SerialThread::run);
if (serial->open(QIODevice::ReadWrite)) {
qDebug() << "Serial port opened successfully";
} else {
qDebug() << "Serial port open failed";
}
}SerialThread::~SerialThread()
{
if (serial->isOpen())
serial->close();
}void SerialThread::run()
{
QByteArray data = serial->readAll();
emit dataReady(data);
}答案:这段代码实现了一个Qt6多线程接收串口的功能,它创建了一个SerialThread类用于读取串口,并在接收到数据时发出dataReady()信号。
阅读全文