Question

I am having real trouble with the use of QProcess, I've looked at several locations to use it, but everytime I use it my program freezes, or it just doesn't do what I want it to do.

What I want to do from my GUI application is the following:

Change directory to /Users/Tim/etc etc. From there I need to call gnuplot and load a script into it.

What I'd normally would do in a terminal window is the following:

 > cd /Users/Tim/...        
 > /opt/local/bin/gnuplot barchartscript.txt

At the moment I'm using system call to do this, and that works, but everybody recommends using QProcess, and so I would like to do that.

How my code looks now with QProcess:

    QObject *parent;
    QProcess *process = new QProcess(parent);
    QString commands;
    QString changed = "cd /Users/Tim/etcetc";
    commands = (changed + "&& /opt/local/bin/gnuplot scatterplotscriptwithout.txt").c_str();

    process->start(commands);

Can anybody tell me what's wrong? Or the correct way to do multiple commands in one process?

Was it helpful?

Solution

This snippet may be useful (untested). Refer to QProcess documentation for detail on each method.

process->setWorkingDirectory("/Users/Tim/etcetc");
process->setArguments(QStringList() << "scatterplotscriptwithout.txt");
process->start("/opt/local/bin/gnuplot");

EDIT

Another thing that seem wrong in your program is the undefined pointer that you give as parent to your QProcess instance. It is useful to set a parent to take benefit of an automatic children deletion. In this case, just take care to delete the QProcess instance yourself.

EDIT 2 (error handling)

QProcess *process = new QProcess;
connect(process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(handleError(QProcess::ProcessError)));

Then define a proper slot (here handleError)

void MyClass::handleError(QProcess::ProcessError error) {
   switch(error) {
   case QProcess::FailedToStart:
    qDebug() << "Failed to start, may be due to insufficient permissions";
    break;
    case QProcess::Crashed:
    qDebug() << "Program crashed.";
    break;
    //debug each case..
   }
}

See here for a detail of all the enum values.

If your QProcess ends correctly but not with the expected output, you can look at the exit code of your process and refer to the gnuplot man page for information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top