Casting a list as QVariant or QVariant List

aarelovich picture aarelovich · Feb 13, 2012 · Viewed 14.3k times · Source

My problem is this. I have lists of different numeric types, for example:

QList<qreal> mylist;

Now, in my code I have a function that that expects a QVariant argument which is mylist. The only way I've found to do this is by using a for cyle and simply adding all of the data in mylist to second list

QList<QVariant> temp, 

for example, and passing temp as a paramter.

I was wondering if there was any other way to do this.

Thank you very much.

Answer

Chris picture Chris · Feb 13, 2012

I've had to do this several times, and to my knowledge the only way is to create a new list.

If this is something you have to do frequently with varying types of lists you could do something a little fancier:

template <typename T>
QVariantList toVariantList( const QList<T> &list )
{
    QVariantList newList;
    foreach( const T &item, list )
        newList << item;

    return newList;
}

so that when you call your function that takes in the QVariant list, you can just call

myFunction( toVariantList(myList) );

Note that the given function will only work for types that can be implicitly converted to QVariants.