Oliver
Oliver

Reputation: 2864

How to run a synchronous chain of QProcess without freezing the gui?

I want to optimize images with the help of some external programs. The programs must be executed one after one, some of them depending on the output of the last program, some of them depending on the characteristics of the image.

I know, I can use signals, but this is not very useful here, because I would have to use dozens of functions and signals for each and every external program, some of them even multiple times depending on the position, where a program is called in the chain. It would be much easier to execute them one by one. But if I do so, the gui freezes immidiately even without displaying the status message until all processes are finished. What else can I do?

ui->status->setText("Do something with program 1");

QProcess *proc1 = new QProcess;
proc1->setReadChannelMode(QProcess::SeparateChannels);
proc1->start("program 1 -args", QIODevice::ReadWrite);

while(!proc1->waitForFinished(10))
    ;

ui->status->setText("Do something with program 2");

QProcess *proc2 = new QProcess;
proc2->setReadChannelMode(QProcess::SeparateChannels);
proc2->start("program 2 -args", QIODevice::ReadWrite);

while(!proc2->waitForFinished(10))
    ;

Upvotes: 1

Views: 2530

Answers (2)

API-Beast
API-Beast

Reputation: 793

In this case using Signals is the "correct" way. You just need to chain them.

[...]
ui->status->setText("Do something with program 1");
proc1.setReadChannelMode(QProcess::SeparateChannels);
proc1.start("program 1 -args", QIODevice::ReadWrite);
connect(proc1, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finishedProc1()))
[...]

void finishedProc1()
{
   ui->status->setText("Do something with program 2");
   proc2.setReadChannelMode(QProcess::SeparateChannels);
   proc2.start("program 2 -args", QIODevice::ReadWrite);
   connect(proc2, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(finishedProc2()))
}

void finishedProc2()
{
  [...]
}

Alternativly you could call processEvents in QApplication while you are waiting or do the whole thing in a different QThread.

Upvotes: 3

alxx
alxx

Reputation: 9897

Create worker thread (several threads, if you need parallel processing) and do waiting there. GUI will not be blocked then.

Upvotes: 0

Related Questions