Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c++ - QSettings::IniFormat values with "," returned as QStringList

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...