In this post I’ll describe the way to deal with Windows Registry in terms of writing and reading Registry Keys. This is done using QSettings class in general, so let’s see how, with a couple of simple examples.
First things first, you need to pass the Registry path to the QSettings class when you construct it. You also need to make sure NativeFormat is chosen as the QSettings class format. Here is how:
QSettings registry("PATH_IN_REGISTRY", QSettings::NativeFormat);
After constructing, you can use allKeys() to get all existing keys within that Registry path. You can also use childKeys() to fetch the keys that are direct children of the provided path. Perhaps the most important method is the value() which can be used to extract a value from Registry.
The example below demonstrates how to get Internet Explorer Build number from Windows Registry:
QSettings registry(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer)", QSettings::NativeFormat); qDebug() << registry.value("Build");
You can check the existence of a certain key in Registry as well, before querying it. Here is an example that shows how we can check the existence of the “Build” key in the preceding example, before actually getting it:
if(registry.childKeys().contains("Build", Qt::CaseInsensitive)) qDebug() << registry.value("Build");
In the preceding examples, there is no need to take any extra measures about the Registry Key type since value() returns a QVariant.
When you want to write using QSettings though, you need to construct it with a few more parameters, namely Format, Scope, Organization and Application title. Here is an example:
QSettings registry(QSettings::NativeFormat, // Format QSettings::UserScope, // Scope "Amin", // Organization "AwesomeApp" // Application );
Now we can use setValue() to write into registry. Here is how:
This will cause the following path to be created in Registry:
With the following key and value pair in it:
Test = 123456
Changing the scope to SystemScope (instead of UserScope) will cause the Registry path to be this:
As you can see, this path is located in HKEY_LOCAL_MACHINE, instead of HKEY_CURRENT_USER. Note that changing the Scope to System will require elevated permissions and you’ll need to open your application in Administrator mode if you’re going to write into Registry. For reading though, you won’t need anything special.