如何在Qt5中使用Windows环境变量

How to use Windows environment variables in Qt5

本文关键字:Windows 环境变量 Qt5      更新时间:2023-10-16

我正在做一个项目,我想从C:/Windows/media访问一个声音文件,但为了保持它更通用,我想使用用户系统中的一些环境变量。

此代码目前有效

soundURL = QUrl::fromUserInput(soundFilename,
                                       QStringLiteral("C:/Windows/media"),
                                       QUrl::AssumeLocalFile);

我尝试了以下代码,不起作用

soundURL = QUrl::fromUserInput(soundFilename,
                                       QStringLiteral((%%WINDIR%%)+"/media"),
                                       QUrl::AssumeLocalFile);

如何利用 %WINDIR% 使路径更简单、更通用?

Qt5公开了几个函数来检索存储在环境变量中的值,即qgetenv和qEnvironmentVariable。

由于您似乎以Windows为目标,因此使用QString qEnvironmentVariable(const char *varName)

更安全
QString winDirPath = qEnvironmentVariable("WINDIR");
if (!winDirPath.isNull()) {
    // the environment variable WINDIR exists and has been retrieved
} else {
    // the environment variable does not exists in this system
}
string path(getenv("WINDIR"));

将 %WINDIR% 放在 std::string 中。我希望你可以对Qt类型做同样的事情。

您可能最好使用Qt标准路径 http://doc.qt.io/qt-5/qstandardpaths.html。弄乱%WINDIR%有点危险。