1

I am using QSettings to parse an ini file: QSettings cfg(path, QSettings::IniFormat);

When I obtain a value QVariant qv = cfg.value("title"); containing a comma the variant contains a QStringList instead of a QString

title=foo => QString
title=foo,bar => QStringList

How can I always get strings, or at least obtain the original line ( title=foo,bar ) ?

4

1 回答 1

4

You have at least two ways to address this issue, all of them presented below:

test.ini

title="foo,bar"
title_unquoted=foo,bar

main.cpp

#include <QSettings>
#include <QDebug>

int main()
{
    QSettings settings("test.ini", QSettings::IniFormat);
    // Original issue
    qDebug() << settings.value("title_unquoted");
    // 1st solution: join the strings
    qDebug() << settings.value("title").toStringList().join(',');
    // 2nd solution: use quotes in the ini file
    qDebug() << settings.value("title");
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

QVariant(QStringList, ("foo", "bar"))
"foo,bar"
QVariant(QString, "foo,bar")

In other words, use quotes for strings with special characters or join the strings manually in the list. The former is far better if it is under your control as you usually ought to aim for proper quoting when using "special" characters in strings.

于 2014-12-19T00:56:36.230 回答