Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand environment variables in Qt (getenv equivalent)

I'm looking for an equivalent of the getenv function.

like image 515
sashoalm Avatar asked Jan 07 '13 16:01

sashoalm


2 Answers

Qt has a wrapper around getenv(), called qgetenv().

QByteArray qgetenv ( const char * varName )

getenv() is a standard function, but Visual Studio has deprecated it which is why Qt provides the qgetenv() wrapper.

Note that if you're interested in getting standard filesystem locations (like the home directory, application data directory, etc.) you should instead use QDesktopServices::storageLocation() (Qt 4) or QStandardPaths::writableLocation() (Qt 5).

like image 157
Nikos C. Avatar answered Oct 10 '22 20:10

Nikos C.


For Qt, there is also a "high-level" approach when accessing environment variables. This only works, if your Qt application runs within a QCoreApplication, which should be the case for most Qt applications.

In that case, you can use QProcessEnvironment, for Qt versions of at least 4.6. You can access the current process environment by using

QProcessEnvironment::systemEnvironment();

and you can query any variable via

QProcessEnvironment::systemEnvironment().value("<variablename>", "<defaultvalue>");

This should be more convenient that using the getenv/qgetenv approach in most cases as this shadows the operating-system implementation in a more generic way and IMHO it is also a more "Qt-alike" approach.

like image 37
nexus Avatar answered Oct 10 '22 19:10

nexus