Qt Execute external program

If your process object is a variable on the stack (e.g. in a method), the code wouldn't work as expected because the process you've already started will be killed in the destructor of QProcess, when the method finishes.

void MyClass::myMethod()
{
    QProcess process;
    QString file = QDir::homepath + "file.exe";
    process.start(file);
}

You should instead allocate the QProcess object on the heap like that:

QProcess *process = new QProcess(this);
QString file = QDir::homepath + "/file.exe";
process->start(file);

QDir::homePath doesn't end with separator. Valid path to your exe

QString file = QDir::homePath + QDir::separator + "file.exe";

If you want your program to wait while the process is executing and only need to get its exit code, you can use

QProcess::execute(file);
QProcess::exitCode(); // returns the exit code

instead of using process asynchronously like this.

QProcess process;
process.start(file);

Note that you can also block execution until process will be finished. In order to do that use

process.waitForFinished();

after start of the process.

Tags:

C++

Qt

External