It's easy to convert a QVector<int> to QVariant but the otherwise is not trivial
QVector<int> v;
v.append(1);
v.append(2);
v.append(3);
QVariant var = QVariant::fromValue(v);
QVector v2(var.toList().toVector()); // fails, returns QVector<QVariant>
First of all: is there any Qt idiom to automatically convert that back or do I have to iterate manually over the var.toList() collection?
Besides, the whole operation is quite costly: first a QList is constructed, then a QVector is constructed, then the QVector is copied back into v2. Is there any way to convert a QVariant directly into QVector? Does Qt support rvalue references itself?
Use QVector<int> v2 = var.value<QVector<int>>();
You can test that by the following piece of code:
QVector<int> v2 = var.value<QVector<int>>();
qDebug() << "Size: " << v2.size();
for(int i = 0; i < v2.size(); i++)
qDebug() << v2.at(i);
Take a look at the method value on Qt documentation:
Returns the stored value converted to the template type T. Call canConvert() to find out whether a type can be converted. If the value cannot be converted, a default-constructed value will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With