Piyush Aggarwal
Piyush Aggarwal

Reputation: 13

How to use Windows environment variables in Qt5

I'm working on a project, where I wanted to access a sound file from C:/Windows/media, but to keep it more general, I want to use some environment variable from the user's system.

This code works At the moment

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

I have tried the below code, doesn't work

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

How can I make use of %WINDIR% to make the path simpler and more general?

Upvotes: 1

Views: 3353

Answers (2)

epsilon
epsilon

Reputation: 2969

Qt5 exposes several functions to retrieve the value stored in an environment variable, namely qgetenv and qEnvironmentVariable.

As you seem to target Windows, the safer is to use 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
}

Upvotes: 2

Michael Surette
Michael Surette

Reputation: 711

string path(getenv("WINDIR"));

will put %WINDIR% in a std::string. I would expect you can do the same with Qt types.

You're probably better off using Qt Standard Paths http://doc.qt.io/qt-5/qstandardpaths.html. Messing with %WINDIR% is a bit dangerous.

Upvotes: 0

Related Questions