I would like to pass the settings saved with QSetting through two instances of an application, for example through a socket.
I could not see any function in the official documentation. The only thing I read is for example this post
Save Configuration Settings to XML file in QT?
But I do not want to save the settings in a XML file, for example in Windows I want to continue using the Registry.
I just want to collect all the settings, and pass them through a socket. And the receiver could check the settings and eventually substitute its own settings with the received ones.
Well, I suppose I could do something similar using QSettings::allKeys(), checking all the values, convert to strings, etc etc...but do you know if there is some native function in Qt already implemented?
Thanks to everyone in advance
Best solution that I found:
Create a QMap from QSettings
QMap<QString, QVariant> keysValuesPairs;
QStringList keys = settings.allKeys();
QStringListIterator it(keys);
while ( it.hasNext() )
{
QString currentKey = it.next();
keysValuesPairs.insert(currentKey, settings.value(currentKey));
}
And then write it in a QJson with the function (see the official documentation http://doc.qt.io/qt-5/qjsonobject.html)
QJsonObject::fromVariantMap
then in the other side recover it with
QJsonObject::toVariantMap()
and rewrite the settings
for ( int i = 0; i < keys.size(); i++ )
{
settings.setValue( keys.at(i), keysValuesPairsMap.value(keys.at(i)) );
}
Related
I want to list all application which had been installed by reading uninstall registry file from HKEY_CURRENT_USER. But look like it can't be done by using QSettings, for some security reason ( i guess ).
QSettings maya("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall
People suggest to use WinAPI to accomplish this (at least, on Window platform)
Can somebody guide me how to add and use this lib please?
Thank
In order to get the list of all sub items under the "Uninstall" one in the Windows registry you need to use QSettings::childGroups() function, i.e:
QSettings m("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
QSettings::NativeFormat);
QStringList ak = m.childGroups();
This will return the list of all installed applications.
UPDATE:
After getting the list of installed applications one can read the installation details. There are two ways for doing that. For example to read the "UinstallPath" key for "Autodesk Maya 2014" application:
m.beginGroup("Autodesk Maya 2014");
QString path = m.value("UninstallPath").toString();
m.endGroup();
or simply:
QString path = m.value("Autodesk Maya 2014/UninstallPath").toString();
In .Net you typically have an app.config file and built in ways to access the configuration.
Is there an equivalent standard approach to configuration using Qt?
For example, lets say my application connects to an online server, I want the ability to store the connection details (user defined).
Is this a case of "roll your own", or is there a way to store and read these configurations using XML, or any other format with easy read/write methods provided by Qt?
Edit: To add some complication to the question. This is a Linux console app, so looking specifically for file based and transparent config please.
You could use QSettings for this. Please refer to the documentation for details:
http://qt-project.org/doc/qt-5.1/qtcore/qsettings.html
You could always use other formats as well like XML, Json, and so forth, but generically speaking, QSettings is the way, or if you are writing a KDE application, then probably KConfig.
These are the two important methods you need to be aware of when dealing with QSettings for reading and writing:
Reading
QVariant QSettings::value(const QString & key,
const QVariant & defaultValue = QVariant()) const
Writing
void QSettings::setValue(const QString & key, const QVariant & value)
Then, you can simply stick to the native format (or even ini on your Linux if you prefer):
QSettings::NativeFormat 0 Store the settings using the most
appropriate storage format for the platform. On Windows, this means
the system registry; on Mac OS X, this means the CFPreferences API; on
Unix, this means textual configuration files in INI format.
Here you can find an example for your convenience:
#include <QSettings>
int main()
{
....
QSettings settings("Foo", "Bar");
// settings.beginGroup("application");
QString string = settings.value("foo", "bar");
// settings.endGroup();
....
}
Note, the groups are optional, and it depends on your exact purpose. You can group settings that way to keep certain ones encapsulated.
This may also be important for you to know as per documentation:
On Unix systems, if the file format is NativeFormat, the following files are used by default:
$HOME/.config/MySoft/Star Runner.conf (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.conf)
$HOME/.config/MySoft.conf (Qt for Embedded Linux: $HOME/Settings/MySoft.conf)
/etc/xdg/MySoft/Star Runner.conf
/etc/xdg/MySoft.conf
I'm an unfortunate beginner at C++ and using the Qt GUI designer program seemed perfect for my needs, except I'm having problems trying to write out the code necessary for this. I could use the QSettings string to store local settings on the hard drive, but I personally hate it when programs do the %HOME_LOCAL%\APPS_SETTINGS bull that some do. I need to save a text file for both settings and a local\host database, within the program directory, to remember strings to read from later.
What is the line of code I need to make use of a local host text database or is there a better option? And how can I store that with the local program inside its directory?
You can use QSettings with any file, with constructor QSettings::QSettings ( const QString & fileName, Format format, QObject * parent = 0 ).
To get the program directory, you can use QCoreApplication::applicationDirPath().
So, answer to your question, statement to put after creation of QApplication instance:
QSettings *settings = new QSettings(
QCoreApplication::applicationDirPath() + "/settings.ini",
QSettings::IniFormat,
qApp);
But, as noted in the comments under question, if you're making your program for general distribution, you should use the OS default. Examine all the constructors of QSettings to see what it can do. User does not often have write permission in the application directory. Note that you can also store settings to Windows registry with QSettings::NativeFormat.
I'm trying to use QHttp for an update app. But there is a problem for me which I can't solve.
I try to download a file (works perfectly) but if there is no connection to the internet, the file is created but has 0 bytes. My old file is then overwritten with the empty file, which is not so good for the application trying to use the file. What I need is to check if the computer is connected to the internet.
Note: proxy may set. I used this example from Qt's homepage.
You should switch to the QNetworkAccessManager as Mike Suggested, here is an example of a slot on the finished() signal:
void ApplicationUpdate::replyFinishedhttpGetChangeLog(QNetworkReply* myReply) {
if (myReply->error() != QNetworkReply::NoError)
{
QByteArray returnedData = myReply->readAll();
if (returnedData.size() > 0) {
if( m_fileChangeLog->exists() )
{
m_fileChangeLog->close();
m_fileChangeLog->remove();
}
m_fileChangeLog->open(QIODevice::ReadWrite);
QDataStream out( m_fileChangeLog );
out.writeRawData(returnedData.data(), returnedData.size());
m_fileChangeLog->flush();
m_fileChangeLog->close();
}
}
}
Firstly, you should probably now be using QNetworkAccessManager rather than QHttp.
Using either of them, you should do a dummy query to a site you pretty much always know will be up (e.g. http://www.google.com/) and use that as a test to see if you have an internet connection.
A better way of doing this would be instead to use QNetworkAccessManager to read into a QByteArray and then check it isn't empty before writing to your file.
Whenever you write a file that might already exist, you should create a QTemporaryFile first, then, after successful download, rename it to the final name.
i ran into the same problem, after a bit of poking around, I've isolated the problem down to the project configuration file (.pro), in the broken configuration I was linking the networking library explicitly with the statement : "LIBS += -lQtNetwork". In the working configuration, I used the more formal (and qt compilant) approach of delcaring what Qt components are included in the project, like so: "QT = core gui network xml", adjust accordingly for your sitiation, the netowkring slots did not work on windows when explicitly linked but did work on linux. Using the qt compilant approach works on both platforms.
linux: $HOME/.config
windows: %APPDATA%
mac os: $HOME/.config
It can be set using http://qt-project.org/doc/qt-4.8/qsettings.html#setPath, but it seems as I am not able to retrieve it.
http://qt-project.org/doc/qt-4.8/qlibraryinfo.html#location QLibraryInfo::LibrariesPath returns the system wide settings dir, which is not what I want.
Any ideas, or do I have to code it separately for each platform?
€: I want to create a sub directory, and store files into it. (You may punish me if this is a bad idea)
This might not answer your question directly: if you want to store per-user persistent data, shouldn't you use QDesktopServices::storageLocation(QDesktopServices::DataLocation) instead?
This is a nasty workaround. First you create QSettings, then get its location.
QSettings cfg(QSettings::IniFormat, QSettings::UserScope,
"organization", "application");
QString config_dir = QFileInfo(cfg.fileName()).absolutePath() + "/";
Credits go to the Qt Centre forum.
QSettings stores the default config in the user AppData directory. See documentation for QSettings. Also this code instructs to store the config in the Ini file format.
this works on both qt 4 and qt 5
QApplication::setApplicationName("MyApp");
QApplication::setOrganizationName("Me");
QString homePath;
#if QT_VERSION >= 0x050000
homePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
homePath = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
Why do you need to know the settings path? If you are going to put settings in it, you could use QSettings. I could see making a subdirectory to hold various settings, but it seems like the easiest way would be to use QSettings directly.
As far as I can tell, you can't retrieve the path. In the Qt source, src/corelib/io/qsettings.cpp, there is a function to get the path:
static QString getPath(QSettings::Format format, QSettings::Scope scope)
{
...
but it's not accessible from code using Qt. You can't copy it and use it either, because it uses internal Qt globals to store the path...
EDIT: A solution was posted, using QDesktopServices.storageLocation(QDesktopServices.DataLocation) but it doesn't do exactly what the question was asking for, i.e. if I set a custom path using QSettings.setPath() it doesn't reflect the change.
What platform are you at?
Might be related or not but in windows, the default is to write QSettings to the registry.
I read more into the question than there was as it was originally posted. It is clearer after the edits. Ok, so can't you use..
QString QSettings::fileName () const
Returns the path where settings are written to using this QSettings object are stored.
On Windows, if the format is QSettings::NativeFormat, the return value is a system registry path, not a file path.