Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Execute external program

Tags:

c++

qt

external

I want to start an external program out of my QT-Programm. The only working solution was:

system("start explorer.exe");

But it is only working for windows and starts a command line for a moment.

Next thing I tried was:

QProcess process;
QString file = QDir::homepath + "file.exe";
process.start(file);
//process.execute(file); //i tried as well

But nothing happened. Any ideas?

like image 544
btzs Avatar asked Oct 18 '13 05:10

btzs


4 Answers

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);
like image 62
tomvodi Avatar answered Nov 08 '22 12:11

tomvodi


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.

like image 27
nv95 Avatar answered Nov 08 '22 12:11

nv95


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

QString file = QDir::homePath + QDir::separator + "file.exe";
like image 42
nnesterov Avatar answered Nov 08 '22 12:11

nnesterov


Just use QProcess::startDetached; it's static and you don't need to worry about waiting for it to finish or allocating things on the heap or anything like that:

QProcess::startDetached(QDir::homepath + "/file.exe");

It's the detached counterpart to QProcess::execute.

As of 5.15 that form is obsolete (but still present). The new preferred call is the same as the above but with a QStringList of command line arguments as the second parameter. If you don't have any arguments to pass just pass an empty list.

like image 37
Jason C Avatar answered Nov 08 '22 12:11

Jason C