QSettings::IniFormat values with “,” returned as QStringList

最后都变了- 提交于 2019-11-28 06:11:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/27557727/qsettingsiniformat-values-with-returned-as-qstringlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!