Iterating over a QVariant that is a QList<int>?

徘徊边缘 提交于 2019-12-13 05:07:11

问题


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();
}

回答1:


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.




回答2:


Try to use QVariant::value:

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



回答3:


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 */ }
}


来源:https://stackoverflow.com/questions/19029623/iterating-over-a-qvariant-that-is-a-qlistint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!