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

Aki*_*iva 0 c++ qt asynchronous signals-slots wait

因此我知道在Qt中,您可以将信号发生后想要的所有内容放到插槽中,但是稍后再编辑代码时就可以了。这可能需要大量的重组,并且可能使事情复杂化。

有没有更简单的方法来保存程序,直到在Qt中发出信号,例如:

downloadImage();
Qt::waitForSignal(downloadImageFinished());
editImage();
Run Code Online (Sandbox Code Playgroud)

也; 为什么这样的东西不起作用:

// bool isFinished();
downloadImage(); // When done, isFinished() returns true;
while (!isFinished()) {}
editImage();
Run Code Online (Sandbox Code Playgroud)

?谢谢。

Leo*_*giy 6

基本上,您应该这样做:

    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
Run Code Online (Sandbox Code Playgroud)

在一个周期内等待将使您的执行线程陷入自旋锁的厄运中-在任何程序中都不应发生这种情况。不惜一切代价避免自旋锁-您不想处理后果。即使一切正常,请记住,您将自己使用整个处理器核心,在这种状态下会大大延迟整体PC性能。