子线程中的 waitForReadyRead() 冻结 GUI 线程

waitForReadyRead() in subthread freezes the GUI thread

抱歉我的英语不好:(

我使用继承自 QObject 的 class 命名的 SerialPort:

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

在 SerialPort::connect() 中,我打开了端口并发送了连接命令。到目前为止一切正常。由于串口速度较慢,我需要在下一步操作之前检查字符串 return,所以在 SerialPort::connect() 中我调用了 checkStatusConnected()。但是,在这个函数中,waitForReadyRead() 冻结了 GUI 线程,只要我设置的时间让我感到困惑。

为什么GUI线程被另一个QThread阻塞,如何解决这个问题?

谢谢!

您不需要为此使用线程。 QSerialPort 是事件驱动的并且异步工作。使用计时器查看您是否在要求的时间内收到了东西。

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
}

找到示例。看看这个,我认为这将满足您的需求。

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