4

In Qt4, there is QProcess::setProcessEnvironment() for setting Env variables for the newly spawn process.

However, QProcess::startDetached() is a static member function, so setProcessEnvironment() doesn't apply. How does one set Env variables for a detached process in Qt?

Giuseppe Cardone
  • 5,323
  • 2
  • 24
  • 30
Shen Chen
  • 123
  • 2
  • 6

3 Answers3

3

It is a known old bug: http://bugreports.qt-project.org/browse/QTBUG-2284. You need to overload startDetached function to support your own environment. Take a look at Qt sources to see how to do that: http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/io?h=5.5 (qprocess* files).

Romário
  • 1,664
  • 1
  • 20
  • 30
Giuseppe Cardone
  • 5,323
  • 2
  • 24
  • 30
  • Overriding startDetached() should be able to solve the problem, will try this tomorrow. Amazed to learn how long this bug has persisted. Having to call putenv() in user code is ugly. This should have been done in Qt. – Shen Chen Nov 24 '10 at 17:55
  • And apparently this bug still hasn't been fixed. I'm using Qt 4.8.4 and am having the same problem. Trying to launch an external console app from my Qt application and would like to see console window but I also need to set various environment settings for that process and that doesn't work when starting it detached. – Jeff Jan 20 '15 at 17:53
3

This behaviour has been fixed in Qt 5.10.0. However, the order of calls seems to be important. The following example works:

QProcess proc;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("var-name", "var-value");
proc.setProgram("program-path");
proc.setProcessEnvironment(env);
proc.startDetached();

while this does not work:

QProcess proc;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("var-name", "var-value");
proc.setProcessEnvironment(env);
proc.startDetached("program-path");
Bowdzone
  • 3,827
  • 11
  • 39
  • 52
0

Using Qt5.5 now, Run into this problem.

Under Win7, Used code below, Set environment in father process, It seems that sub process inherit the environment. Not for sure, but it worked in my case.

Hope there is better solutions

QString oldPath = qgetenv( "Path" );
QByteArray newPath = ( QCoreApplication::applicationDirPath() + ";" + oldPath ).toLocal8Bit();
bool bSet = qputenv("Path", newPath);
if ( !bSet )
{
    qDebug()<<"Failed";
}
Ian.Zhang
  • 151
  • 1
  • 10