Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set PATH variable using QT?

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.

like image 618
Hossein Avatar asked Jul 05 '13 13:07

Hossein


3 Answers

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 :)

like image 189
S.M.Mousavi Avatar answered Sep 28 '22 16:09

S.M.Mousavi


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.

like image 45
exrook Avatar answered Sep 28 '22 15:09

exrook


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.

like image 28
mortalis Avatar answered Sep 28 '22 15:09

mortalis