QSerialPort readyread() 信号

QSerialPort readyread() SIGNAL

我在 QByteArray 中从 RS232 接收字节时遇到问题。我连接了 readyread() 信号来调用我的串行端口方法,在其中我正在使用 readAll() 将字节读取到 QByteArray。只要数据可用,它就会重写 QByteArray,但我想接收所有数据,然后使用数据,但现在我不能,因为它是部分的。怎么办?

简单地附加到数组。您还需要一些标准来确定何时收到了您想要的所有数据。这可以是,例如给定的字节数:

class Communicator {
  int expect;
  QSerialPort port;
  QByteArray reply;
  void processReply() {
    ...
  }
public:
  Communicator() {
    QObject::connect(&port, &QIODevice::readyRead, [this]{
      reply += port.readAll();
      if (expect && reply.size() >= expect) {
        processReply();
        reply.clear();
        expect = 0;
      }
    });
  ...
};