在我的应用程序中,我从本地应用程序数据文件夹运行分离的进程。下面的代码适用于大多数情况。
void executeApp(const QString &id)
{
QString program = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
program = program + "\..\Programs\MyApp.exe";
QStringList arguments;
arguments << "--app_id="+id; //it is only one argument
QProcess* process = new QProcess(this);
bool success = process->startDetached(program, arguments);
if (!success) //TODO: Error handling
qDebug() << "Couldn't start process at " << program << process->errorString();
}
运行一些测试,我发现当 Windows 帐户用户名中包含空格时它不起作用(Windows 实际上允许这样做)。
如何解决这个问题?
---编辑:
根据发布的答案,我对代码进行了一些更改。但是,我仍然从下面的代码中在QMessageBox上收到"未知错误":
void executeApp(const QString &id)
{
QString program = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
program = QDir(program + "/../Programs/MyApp.exe").absolutePath();
QStringList arguments;
arguments << "--app_id="+id; //it is only one argument
QProcess* process = new QProcess(this);
bool success = process->startDetached(program, arguments);
if (!success)
QMessageBox::critical(NULL, tr("Launching App"), process->errorString());
}
加强的是,只有当用户名中有一个空格的用户时,才会发生这种情况......
QString QDir::absolutePath() const
返回绝对路径(以"/"或驱动器开头的路径) 规范),可能包含符号链接,但绝不包含 冗余的"."、".."或多个分隔符。
将路径从根转换为绝对形式是有意义的:
QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
QString exePath = QDir(dataPath + "/../Programs").absolutePath();
qDebug() << "Executable path" << exepath;
qDebug() << "File exists" << QFile(exepath + "/MyApp.exe").exists();
至于另一个问题,由于路径中包含的用户名中的空格,它无法运行可执行文件。我们应该将整个路径括在引号中,以便 Windows CreateProcess 满足:
process->startDetached(QStringLiteral(""") + exepath + "/MyApp.exe" + QChar("""), arguments);
请注意,Qt通常能够接受路径参数的反斜杠"\"和斜杠"/"分隔符。
您可以尝试使用 QDir 解析路径:
QDir dataDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation));
QString program = dataDir.absolutePath("../Programs/MyApp.exe");