Anon
Anon

Reputation: 2492

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

So I know in Qt, you can just put everything you want after a signal to happen into a slot, but when editting code later on; that can require a lot of restructuring, and may complicate things.

Is there a more simple way to hold your program until a signal is emitted in Qt, like say for example:

downloadImage();
Qt::waitForSignal(downloadImageFinished());
editImage();

Also; why doesn't something like this work:

// bool isFinished();
downloadImage(); // When done, isFinished() returns true;
while (!isFinished()) {}
editImage();

? Thanks.

Upvotes: 1

Views: 4814

Answers (2)

eff
eff

Reputation: 417

As the working of downloadImage is in another thread you can use a Qt::BlockingQueuedConnection (Qt documentation). This waits for a slot to complete prior to continuing with execution:

connect (this, &ThisType::triggerImageDownload,
         otherObject, &OtherType::downloadImage,
         Qt::BlockingQueuedConnection);

then

emit triggerImageDownload(); // This now blocks until downloadImage completes
editImage();

Upvotes: 0

Leontyev Georgiy
Leontyev Georgiy

Reputation: 1315

Basically, you should do this:

    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

Wait inside a cycle will put your execution thread into a doom of spinlock - this shouldn't happen in any program. Avoid spinlocks at all cost - you don't want to deal with the consequences. Even if everything works right, remember that you will take whole processor core just for yourself, significantly delaying overall PC performance while in this state.

Upvotes: 12

Related Questions