所以我知道在 Qt 中,你可以将信号发生后想要的所有内容放入插槽中,但是稍后编辑代码时;这可能需要大量的重组,并且可能会使事情变得复杂。
是否有更简单的方法来保存程序,直到 Qt 中发出信号,例如:
downloadImage();
Qt::waitForSignal(downloadImageFinished());
editImage();
还有;为什么这样的东西不起作用:
// bool isFinished();
downloadImage(); // When done, isFinished() returns true;
while (!isFinished()) {}
editImage();
?谢谢。
基本上,你应该这样做:
QEventLoop loop;
connect(this, &SomeObject::someSignal, &loop, &QEventLoop::quit);
// here you can send your own message to signal the start of wait,
// start a thread, for example.
loop.exec(); //exec will delay execution until the signal has arrived
在循环内等待将使您的执行线程陷入自旋锁的厄运 - 这不应该在任何程序中发生。不惜一切代价避免使用自旋锁——你不想承担后果。即使一切正常,请记住,您将占用整个处理器核心,从而在这种状态下显着延迟整体 PC 性能。
由于
downloadImage
的工作在另一个线程中,因此您可以使用 Qt::BlockingQueuedConnection
(Qt 文档)。这会在继续执行之前等待槽完成:
connect (this, &ThisType::triggerImageDownload,
otherObject, &OtherType::downloadImage,
Qt::BlockingQueuedConnection);
然后
emit triggerImageDownload(); // This now blocks until downloadImage completes
editImage();