在 Qt 中让程序等待信号的最简单方法是什么?

What is the simplest way to make your program wait for a signal in Qt?

所以我知道在 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 性能。