Qt在Windows下使用waitForconnected()或者其它waitFor…系列函数,会随机失效(Qt官网的解释),我自己也是碰到过这个问题。如果不用waitFor…系列函数,怎样实现阻塞等待的功能呢。用QEventloop和QTimer可以实现这个功能。
bool QtWidgetsApplication1::WaitForSignalFinished3(const char * signal, const unsigned int millisecond)
{
bool result = true;
QEventLoop loop;
connect(this, signal, &loop, SLOT(quit()));
QTimer timer;
timer.setSingleShot(true);
connect(&timer, &QTimer::timeout, [&loop, &result] { result = false; loop.quit(); });
timer.start(millisecond);
loop.exec();
timer.stop();
return result;
}
核心点是使用QEventLoop阻塞当前程序,如果有信号发出,则loop->exec()正常退出,返回true;如果信号在millisecond时间内没有发出,定时器会触发。使用Lambda将result置为false。此时loop->exec()退出时会返回false。