文档上已经解释得很清楚了:
void QIODevice::readyRead() [信号]
每当从设备中有新数据可供读取时,都会发出此信号。仅在再次有新数据可用时才会重新发出信号,例如当网络套接字上到达新的负载或者将新的数据块附加到设备时。
readyRead() 不是递归发出的;如果您在连接到 readyRead() 信号的槽函数内重新进入事件循环或调用 waitForReadyRead(),则不会重新发出信号(但 waitForReadyRead() 可能仍会返回 true)。
对于实现自 QIODevice 派生类的开发人员,请注意:只有在有新数据到达时才发出 readyRead()(不要仅因为缓冲区中仍有数据可读而发出它)。不要在其他情况下发出 readyRead()。
这意味着不能保证有多少数据可供读取,只是有一些可用。
如果你想读取比一次接收更多的数据,可能需要使用超时值和/或 readyRead。这取决于你想要实现的目标。
此外,您还可以查看我之前编写的一个命令行异步读取器示例来了解此操作。
#include "serialportreader.h"
#include <QCoreApplication>
QT_USE_NAMESPACE
SerialPortReader::SerialPortReader(QSerialPort *serialPort, QObject *parent)
: QObject(parent)
, m_serialPort(serialPort)
, m_standardOutput(stdout)
{
connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
m_timer.start(5000);
}
SerialPortReader::~SerialPortReader()
{
}
void SerialPortReader::handleReadyRead()
{
m_readData.append(m_serialPort->readAll());
if (!m_timer.isActive())
m_timer.start(5000);
}
void SerialPortReader::handleTimeout()
{
if (m_readData.isEmpty()) {
m_standardOutput << QObject::tr("No data was currently available for reading from port %1").arg(m_serialPort->portName()) << endl;
} else {
m_standardOutput << QObject::tr("Data successfully received from port %1").arg(m_serialPort->portName()) << endl;
m_standardOutput << m_readData << endl;
}
QCoreApplication::quit();
}
void SerialPortReader::handleError(QSerialPort::SerialPortError serialPortError)
{
if (serialPortError == QSerialPort::ReadError) {
m_standardOutput << QObject::tr("An I/O error occurred while reading the data from port %1, error: %2").arg(m_serialPort->portName()).arg(m_serialPort->errorString()) << endl;
QCoreApplication::exit(1);
}
}
在这种情况下,命令行读取器示例会一次性获取传递的任何数据,但它不能保证长度或其他任何内容。
另外,请注意,在您评论后面的同步API与您所询问的异步API不太相关。我指的是 m_serialPort->waitForReadyRead(200);
。