0

I tri to append a QVariant to another QVariant (which must be a QVariantList).

QList<int> listInt;
listInt.append(1);    
QVariant v;
v.setValue(listInt);
if(v.canConvert(QVariant::List))
{
    QVariant v1;
    v1.setValue(5);
    qvariant_cast<QVariantList>(v).append(v1);
}
objC.setProperty("_list", v);

But in the obC my _list contains only the integer 1. What is the problem?

artoon
  • 729
  • 2
  • 14
  • 41

1 Answers1

1

The problem is, that the qvariant_cast<> returns by-value. So with your call to append() you are not changing the original object but only the copy. To make the changes stick, you will have to reset the QVariant, e.g.

    ...
    QVariantList toChange = qvariant_cast<QVariantList>(v);
    toChange.append(v1);
    v.setValue(toChange);
    ...

or using QList<int> instead of QVariantList

    ...
    QList<int> toChange = qvariant_cast< QList<int> >(v);
    toChange.append(47);
    v.setValue(toChange);
    ...
Steffen
  • 2,888
  • 19
  • 19
  • Ok. With your solution I have two items in `_list` but items are corrumpted (thay are not 1 and 5) – artoon Sep 02 '14 at 14:11
  • 1
    This answer was the first one. So I just place here a working example for you. Run it on your computer, not in ideone: http://ideone.com/nv9wYN – Ezee Sep 02 '14 at 14:23
  • Your example works but, at the begining, I must have a QList and at the end I must have also a QList (and not a QVariantList). – artoon Sep 02 '14 at 14:33
  • Then you can put in QList as the type parameter for the qvariant_cast and you should get the correct type back. – Steffen Sep 02 '14 at 14:45
  • The problem is when I do the append I don't know the type T so I must only use generic type. – artoon Sep 03 '14 at 07:49
  • Not sure if I understand, what you are trying to do... You could make a template function with T as template parameter to do this. But this would of course fall flat if you were to try to add say an int to a QList this way. And if type T gets more complex you may have to make them known to Qt's meta type system. – Steffen Sep 04 '14 at 07:32