Search code examples
c++qtserial-portqtserialport

QSerialPort readyread() SIGNAL


I have a problem when receiving bytes from RS232 in QByteArray. I connected readyread() signal to call my serialport method and inside it I am reading bytes with readAll() to an QByteArray. Whenever data is available it rewrites QByteArray, but I want to receive it all, and then use data, but now I cannot because it is in parts. What to do?


Solution

  • Simply append to the array. You'll also need some criterion to determine when you've received all the data you wished. This can be, e.g. a given number of bytes:

    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;
          }
        });
      ...
    };