问题
It is possible to convert QList<YourType>
to QVariant
provided you declare your type as q meta type using this macro:
Q_DECLARE_METATYPE(MyType);
After that, the conversion is even implicit:
QList<MyType> list;
QVariant variant = QVariant::fromValue(list);
Now my question is how to convert variant
back to QList<MyType>
.
回答1:
QVariant
provides method canConvert<T> that you can use to check:
if( variant.canConvert<QList<MyType>>() ) {
QList<MyType> list = variant.value<QList<MyType>>();
...
}
回答2:
Just to clearly combine what I got in comments and the accepted answer.
QList<MyType> convertToMyType(QVariant variant) {
if( variant.canConvert<QList<MyType>>() ) {
return variant.value<QList<MyType>>();
}
else {
// Exception? Empty list?
// depends on circumstances
}
}
来源:https://stackoverflow.com/questions/36623931/can-i-conveniently-converty-qvariant-back-to-qlistmytype