QAssociativeIterable
类是QVariant
中一个关联式容器的可迭代接口。这个类允许多种访问在QVariant
中保存的关联式容器元素的方法。如果一个QVariant
可以转换为QVariantHash
或QVariantMap
,那么QAssociativeIterable
的实例可以从中提取出来。
QHash<int, QString> mapping;
mapping.insert(7, "Seven");
mapping.insert(11, "Eleven");
mapping.insert(42, "Forty-two");
QVariant variant = QVariant::fromValue(mapping);
if (variant.canConvert<QVariantHash>()) {
QAssociativeIterable iterable = variant.value<QAssociativeIterable>();
// Can use foreach over the values:
foreach (const QVariant &v, iterable) {
qDebug() << v;
}
// Can use C++11 range-for over the values:
for (const QVariant &v : iterable) {
qDebug() << v;
}
// Can use iterators:
QAssociativeIterable::const_iterator it = iterable.begin();
const QAssociativeIterable::const_iterator end = iterable.end();
for ( ; it != end; ++it) {
qDebug() << *it; // The current value
qDebug() << it.key();
qDebug() << it.value();
}
}
结果: