Can I conveniently converty QVariant back to QList<MyType>?

删除回忆录丶 提交于 2019-12-12 19:16:17

问题


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

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