How can I get and set PATH variable using QT 4.8? I know I can get PATH variable values using getenv from the STL but don't know how to set it using STL or any Qt based method?
If QT has a function for it, I would like to know and use it rather than going and using Windows API for it.
Thanks to my friend Mr. Toosi, you can set environment variable for current process using qputenv("key", "value")
and get it using qgetenv("key")
.
This works on Qt 5.5.0 too :)
You can use setenv from stdlib.h to set PATH to a new value.
setenv("PATH","/new/path/value",1)
However, this is a non-standard extension to the standard headers, and will only affect sub-processes spawned by the calling process. In order to change environment variables for all new processes spawned, a system-specific method must be used. For windows, the PATH variable can be changed in the
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
registry key. This will make sure the PATH is set for all new processes, and will apply over a reboot.
I worked with the Registry
value using this code:
Include:
#include <windows.h>
To read:
QSettings setting( "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", QSettings::NativeFormat );
QString pathVal = setting.value("Path", "no-path").toString();
To write:
setting.setValue( "Path", path );
SendMessageA( HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment" );
This way I get the actual Path
value without reloading the program and write the value broadcasting the change to all processes.
Couldn't realize first how to use SendMessage
from this answer:
How to modify the PATH variable definitely through the command line in Windows.
I thought I should create a Win32
app in Visual Studio and then send this message inside of it.
But this function should be called just after the registry changed. So I could edit the registry value manually and then press a button which called the SendMessageA
and the Path
updated.
BTW, there is SendMessage
macro which calls SenMessageW
function but it didn't work and the Path
didn't change. Don't know what the A
means but it changes the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With