How to run a detached application by terminal command in Qt application?

旧巷老猫 提交于 2019-12-10 19:08:30

问题


I want to use commands:

cd /opencv/opencv-3.0.0-alpha/samples/cpp/
./cpp-example-facedetect lena.jpg

to run a sample code of OpenCV on clicked() method of button in Qt application. So I use:

void MainWindow::on_btSample_clicked()
{
        QProcess process1;
        QProcess process2;

        process1.setStandardOutputProcess(&process2);

        process1.start("cd /opencv/opencv-3.0.0-alpha/samples/cpp");
        process1.waitForBytesWritten();
        process2.start("./cpp-example-facedetect lena.jpg"); 
}

I added necessary library to use it. But I have an error when I run my application.

QProcess: Destroyed while process ("./cpp-example-facedetect") is still running.

How can I fix it? If the way I make isn't right, plz give me another way. Thank u in advance!


回答1:


I think you have two issues here:

Firstly your QProcess process2 is probably going out of scope before it finishes (i.e. gets destroyed since its out of scope). You either have to wait for it to finish (using waitForFinished(), or make it a pointer or member variable (to change the scope) and connect the finished() signal to some handling slot (which can do the tidy up).

The other thing here is, it looks like you just want to set the working directory, so I don't think piping the cd command into your executable is the way to go, it would be easier to do something like:

EDIT

I have edited my example to show you how to get the output:

QProcess myProc;

qDebug() << "Starting process\n";
// Setup the working directory
QDir::setCurrent("D:\\software\\qtTest");

// Start the process (uses new working dir)
myProc.start("test.bat");

myProc.waitForFinished();
qDebug() << myProc.readAll();

I knocked this up on my windows box in about 2 minutes and tested it for you... I could do it on linux but that will take me a little longer because I have to boot it up :o ... but if you want I will.

EDIT 2

If you want to detach the process entirely:

QProcess myProc;

qDebug() << "Starting process\n";
// Setup the working directory
QDir::setCurrent("D:\\software\\qtTest");

// Start the process (uses new working dir)
myProc.startDetached("test.bat");

Now I am not 100% sure you can get the output back from the process... it is now nothing to do with your Qt app...



来源:https://stackoverflow.com/questions/36593993/how-to-run-a-detached-application-by-terminal-command-in-qt-application

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