我正在开发一个小型客户端-服务器应用程序。客户端发送查询请求并需要等待答案。我认为最方便的方法是使用QEventLoop:
connect(&parser, SIGNAL(answer_received()), this, SLOT(react_to_answer()));
...
...
QEventLoop loop;
connect(&parser, SIGNAL(answer_received()), &loop, SLOT(quit()));
this.sendQuery();
loop.exec();
这个方法目前对我有效,但如果answer_received()
信号在调用loop.exec()
之前非常快地被触发,会发生什么呢?我的应用程序会一直卡在QEventLoop中吗?
谢谢!
QEventLoop::exec()
会将QEventLoopPrivate::exit
设置为false
,因此调用QEventLoop::quit()
并不能阻止事件循环的运行。 - Benjamin TsendQuery()
调用期间调用quit()
槽,特别是因为连接更像是简单的函数调用而不是事件。为了确保在loop.exec()
之后调用quit()
,必须以某种方式强制通过 Qt 事件系统进行,例如显式指定连接是排队的。 - Benjamin T