A lucky ant
A lucky ant

Reputation: 109

waitForReadyRead() in subthread freezes the GUI thread

Sorry for my poor English :(

I use a class named SerialPort inherited from QObject:

serial_port.cpp & serial_port.h:

class SerialPort: public QObject{
    Q_OBJECT
private:
    bool checkStatusConnected();

private slots:
    void readData();
}



bool SerialPort::checkStatusConnected(){
    port.waitForReadyRead(200);
    QBytesArray recv = port.readAll();
    QString tmp = (QString)recv;
    if(tmp.contains("Connected", Qt::CaseInsensitive))
        return true;

    return false;
}

MainWindow.cpp

void MainWindow::on_btnConn_clicked()
{
    QThread* thread = new QThread(this);
    serialport->moveToThread(thread);
    serialport->connect();
}

In SerialPort::connect() I opened the port and send the connect command. Till now everything is ok. Due to slow speed of serial port I need to check the string return to me before next actions, so in SerialPort::connect() I call checkStatusConnected(). However, in this function waitForReadyRead() freezes the GUI thread as long as the time I set which makes me confused.

Why is the GUI thread blocked by another QThread and how to solve this problem?

Thanks!

Upvotes: 0

Views: 702

Answers (1)

ramtheconqueror
ramtheconqueror

Reputation: 1964

You don't need to use threads for that. QSerialPort is event driven and works asynchronously. Use a timer to see whether you have received something within the required time.

QSerialPort port(....);
connect(&port, SIGNAL(readyRead()), this, SLOT(readFromSerialPort()));
QTimer timer;
timer.setInterVal(1000); // time you want to wait
connect(&timer, SIGNAL(timeout()), this, SLOT(handleTimeout()));

void SomeClass::readFromSerialPort()
{
 QByteArray data(port.readAll());
 // do somework
}

Found the examples. Check this out, this will suffice your needs I think.

http://doc.qt.io/qt-5/qtserialport-creaderasync-example.html

Upvotes: 1

Related Questions