[英]QSettings how to save QMap<QString,int> into configuration file
After reading Save QList<int>
to QSettings
, I'm tring to do the same with QMap<QString,int>
. 在阅读Save
QList<int>
到QSettings
,我想对QMap<QString,int>
做同样的事情。 I would like the configuration file to look like this: 我希望配置文件看起来像这样:
1111=1
2222=3
4444=0
But I'm getting a compilation error: 但是我收到了编译错误:
Q_DECLARE_METATYPE(QMap<QString,int>)
Warning C4002: too many actual parameters for macro 'Q_DECLARE_METATYPE'
ConfigSettings.h(5) : error C2976: 'QMap' : too few template arguments
The error message you're getting is caused by the fact that the preprocessor doesn't know about templates. 您获得的错误消息是由预处理器不知道模板的事实引起的。 So it's parsing that macro call is if it had two arguments -
QMap<QString
and int>
, which makes no sense. 因此它解析宏调用是否有两个参数 -
QMap<QString
和int>
,这没有任何意义。
To save the data as you want it, you're better of serializing it yourself to your QSettings
. 要根据需要保存数据,最好自己将其序列化到
QSettings
。 Something like this for writing: 写这样的东西:
settings.beginGroup("Whatever");
QMap<QString, int>::const_iterator i = map.constBegin();
while (i != map.constEnd()) {
settings.setValue(i.key(), i.value());
++i;
}
settings.endGroup();
To read the settings, use the same approach with the help of the childKeys()
function. 要读取设置,请在
childKeys()
函数的帮助下使用相同的方法。
settings.beginGroup("Whatever");
QStringList keys = settings.childKeys();
foreach (QString key, keys) {
map[key] = settings.value(key).toInt();
}
settings.endGroup();
QSetting
accept QVariant
type to pass into setValue
method, so it means that you can store QMap<QString, QVarint>
map directly to settings QSetting
接受QVariant
类型传递给setValue
方法,这意味着你可以将QMap<QString, QVarint>
map直接存储到设置中
// Store
QMap<QString, QVariant> storeMap;
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
storeMap[it.key()] = QVariant(it.value());
it.next();
}
settings.setValue("myKey", storeMap);
..
// Read
QMap<QString, QVariant> readMap = settings.value("myKey").toMap();
QMapIterator it(readMap);
while(it.hasNext())
{
myMap[it.key()] = it.value().toInt();
it.next();
}
I understand the accepted answer, but I think the original question was how to store the QMap. 我理解接受的答案,但我认为最初的问题是如何存储QMap。 It devolved into how to make the compiler behave.
它转变为如何使编译器行为。
QSettings mySettings...
QMapIterator it(myMap);
// iterate through the map to save the values in your chosen format
while(it.hasNext())
{
it.next();
mySettings.setValue(it.key(), it.value());
}
If however you wish to store this along with a bunch of other settings or data structures, you might consider using "beginGroup()" and "endGroup()" to group a bunch of different data structures into one file. 但是,如果您希望将其与一堆其他设置或数据结构一起存储,则可以考虑使用“beginGroup()”和“endGroup()”将一堆不同的数据结构分组到一个文件中。 Very tidy and readable.
非常整洁和可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.