Qt: QProcess to call terminal + script

房东的猫 提交于 2019-12-22 18:39:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20841116/qt-qprocess-to-call-terminal-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!