Set Environment Variables for startDetached() QProcess

旧巷老猫 提交于 2019-11-29 16:33:29
Giuseppe Cardone

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).

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";
}

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