Convert QVariantList to QList<Type> list
-
Hi All
I have a QVariantList which is passed as a parameter to my function.
void myfunc(const QVariantList &list) { // I want to convert this to QList<Type> newList // where Type is the type() of list.at(0) // the variant list consists of variants all of the same type }
What I want to do is
QList<Type> newList; //how do I declare this if I dont know the Type foreach(QVariant v, list) newList << v.value();
Then create a QSet from the newList
Is there a way of easily achieving this
Regards
Ikim
-
Hi and welcome to devnet,
Do you mean
QSet<Type> newSet = newList.toSet();
?
If so, why not:
QSet<Type> newSet; foreach(QVariant v, list) { newSet << v.value<Type>(); }
?
-
What is your use case ?
-
QVariant has the == operator
-
No, use the QSet features e.g.
QSet<QVariant> commonSet = mySet1 & mySet2;
-
mmmm, You're right.
So I suggest to create a
template
methodThis code works for me
template <typename T> QSet<T> mergeList(const QVariantList& l1, const QVariantList& l2) { QSet<T> s1, s2; for (const QVariant& v: l1) { s1.insert(v.value<T>()); } for (const QVariant& v: l2) { s2.insert(v.value<T>()); } return s1 & s2; }
Used as
QVariantList l1, l2; l1 << 1 << 2 << 3; l2 << 1 << 3 << 5; QSet<int> s1 = mergeList<int> (l1, l2); qDebug() << s1; l1.clear(); l2.clear(); l1 << "Foo" << "Bar"; l2 << "Bar" << "Fred"; QSet<QString> s2 = mergeList<QString> (l1, l2); qDebug() << s2;