Pregunta

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.

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top