gpt4 book ai didi

c++ - 将 QPair 的 QList 写入 QSettings 对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:25 35 4
gpt4 key购买 nike

我有一个整数对列表,我想使用 Qt Framework 以持久的方式存储它们。

我想到了使用 QList< QPair < int,int>>作为列表的类型,并使用 QSettings 将它们存储在 .ini 文件中.

不幸的是,函数QSettings::setValue引发错误:

no matching function for call to ‘QSettings::setValue(const char [19], FavoriteList&)’
note: no known conversion for argument 2 from QList< QPair< int, int> > to ‘const QVariant&’

它似乎无法将该类型转换为 QVariant .我尝试用 Q_DECLARE_METATYPE 声明它但它没有用,它引发了同样的错误。

如何将该类型写入 QSettings对象?

编辑:失败的代码示例:

QList<QPair<int,int>> list;

if(!settings.contains("Radio/Favorites/FM"))
{
settings.setValue("Radio/Favorites/FM", list);
}

最佳答案

您只是没有任何兼容的隐式转换。编译器不知道如何将您的列表转换为变体。

事实上,Q_DECLARE_METATYPE 根本不是必需的,至少对我而言,以下代码编译没有错误:

  QSettings s;
QList< QPair < int,int>> l;
s.setValue("key", QVariant::fromValue(l));

编辑:虽然它不会出现编译错误,但它仍然会出现运行时错误,因为它不知道如何序列化和反序列化一个 int 对列表。所以你必须告诉它如何:

QDataStream &operator<<(QDataStream &out, const QList<QPair<int,int>> &l) {
int s = l.size();
out << s;
if (s) for (int i = 0; i < s; ++i) out << l[i].first << l[i].second;
return out;
}
QDataStream &operator>>(QDataStream &in, QList<QPair<int,int>> &l) {
if (!l.empty()) l.clear();
int s;
in >> s;
if (s) {
l.reserve(s);
for (int i = 0; i < s; ++i) {
int f, sec;
in >> f >> sec;
l.append(QPair<int, int>(f, sec));
}
}
return in;
}

并且还在元系统中为该类型注册流运算符:

qRegisterMetaTypeStreamOperators<QList<QPair<int,int>>>("whatever");

Aaand.. 它有效!

  QSettings s;
QList<QPair<int,int>> l;
l.append(QPair<int, int>(555, 556));
s.setValue("key", QVariant::fromValue(l));
QList<QPair<int,int>> l1 = s.value("key").value<QList<QPair<int,int>>>();
qDebug() << l1.at(0).first << l1.at(0).second; // 555 556

关于c++ - 将 QPair 的 QList 写入 QSettings 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031452/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com