1
votes

I'm using QObject's dynamic property to store information to be used in a Slot that can access said property. The sender is a QState with: myQState->setProperty("key", QList<int>(0, 1, 2));

I would like to convert the stored QVariant back to a QList so it can be iterated. The following code does not work (error C2440: QVariant can't be converted to QList with {[T=int]):

QVariant vprop = obj->property("key");
QList<int> list = vprop; //   < - - - - - - - - ERROR
foreach (int e, list )
{
    qDebug() << __FUNCTION__ << "" << e;
}

This code works. The object to set as property:

QVariantList list;
list.append(0);
list.append(1);
list.append(2);

And in the slot

QObject *obj = this->sender();
foreach( QByteArray dpn, obj->dynamicPropertyNames() )
{
    qDebug() << __FUNCTION__ << "" << dpn;
}
QVariant vprop = obj->property("key");
qDebug() << __FUNCTION__ << "" << vprop;
QVariantList list = vprop.toList();
foreach(QVariant e, list )
{
    qDebug() << __FUNCTION__ << "" << e.toInt();
}
3
ok the code posted does not work at all..just a momenthandle

3 Answers

5
votes

Or use QList<QVariant> QVariant::toList () const

QList<QVariant> list = vprop.toList();

And than iterate over the items and convert each to integer if needed.

3
votes

Try to use QVariant::value:

QList<int> list = vprop.value< QList<int> >();
1
votes

Since the question was posted Qt has started providing a more efficient way to iterate over a QVariant that contains an iterable value, like QList<T>, rather than converting all of it to a QList<QVariant>. You basically have to get the value of the QVariant as an QSequentialIterable:

QList<int> intList = {7, 11, 42};
QVariant variant = QVariant::fromValue(intList);
if (variant.canConvert<QVariantList>()) {
  QSequentialIterable iterable = variant.value<QSequentialIterable>();
  for (const QVariant& v: iterable) { /* stuff */ }
}