Code works using waitForReadyRead(), doesn't work when connecting slot to readyRead()



  • I'm trying to read data from a serial connection.

    When I'm using a blocking function, the data is read and processed correctly but I can't display it in the GUI. So I tried reading the data like it's done in the Command Line Reader Async Example. But handleReadyRead() is never called and I don't know why. I'm new to Qt, so I might have overlooked something fundamental.

    void Window::read()
    {
        QSerialPort serialPort;
        serialPort.setPortName("COM4");
    
        serialPort.open(QIODevice::ReadOnly);
    
        // omitted some serial port configuration
    
        //    while(1)
        //    {
        //        if(serialPort.waitForReadyRead(1000))
        //        {
        //            //Data was returned
        //            QByteArray input = serialPort.readAll();
        //            //qDebug()<<"Response: "<< input;
        //            QList<QByteArray> extracted = input.split('\n');
        //            //qDebug()<<"Response: "<< extracted;
        //            qDebug()<<"Response: "<< extracted.at(1);
        //        }
        //    }
    
        connect(&serialPort, SIGNAL(readyRead()), this, SLOT(handleReadyRead()));
    }
    
    
    void Window::handleReadyRead()
    {
        QByteArray input = serialPort.readAll();
        //qDebug()<<"Response: "<< input;
        QList<QByteArray> extracted = input.split('\n');
        //qDebug()<<"Response: "<< extracted;
        qDebug()<<"Response: "<< extracted.at(1);
    }
    


  • I suggest you to use waitForReadyRead() in a thread without the events approach.
    If you don't want to use threads please use readyRead() event without waitForReadyRead().



  • Thanks, I'll try usig threads.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    There's no need for threads here. What happens is that you declare serialPort in your read function thus it's a local variable that will be destroyed at the end of the function.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.