subthread中的waitForReadyRead()冻结了GUI线程

时间:2015-12-03 12:22:18

标签: multithreading qt qthread

抱歉我的英语不好:(

我使用一个名为SerialPort的类继承自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();
}

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您不需要使用线程。 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