How can I cast a QVariant to custom class?

烈酒焚心 提交于 2019-11-29 01:52:42

You could try using qvariant_cast and qobject_cast.

QObject *object = qvariant_cast<QObject*>(selectItem);
Category *category = qobject_cast<Category*>(object);

Also, never put any persistent statement into Q_ASSERT. It will not be used when the assert is not enabled.

EDIT: works for non QObject derived type (see Final Contest's answer for this case)

First of all, you need to register your type to be part of QVariant managed types

//customtype.h
class CustomType {
};

Q_DECLARE_METATYPE(CustomType)

Then you can retrieve your custom type from QVariant in this way :

CustomType ct = myVariant.value<CustomType>();

which is equivalent to:

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