如何将QVariant转换为自定义类?

J.M*_*M.J 12 c++ qt cascade qvariant blackberry-10

我正在使用Momentics IDE(本机SDK)开发BlackBerry 10移动应用程序.

我有一个listview,我想用C++来处理它的项目(我需要使用C++而不是QML).

我可以使用"connect"指令获取索引路径,但是我将QVariant解析为自定义类有问题;

Q_ASSERT(QObject::connect(list1, SIGNAL(triggered(QVariantList)), this, SLOT(openSheet(QVariantList))));

QVariant selectItem = m_categoriesListDataModel->data(indexPath);
Run Code Online (Sandbox Code Playgroud)

我尝试使用如下的静态演员

Category* custType = static_cast<Category*>(selectItem);
Run Code Online (Sandbox Code Playgroud)

但它返回:

"invalid static_cast from type 'QVariant' to type 'Category*'"
Run Code Online (Sandbox Code Playgroud)

谁可以帮我这个事 ?

eps*_*lon 19

编辑:适用于非QObject派生类型(参见本次案例的最终竞赛答案)

首先,您需要注册您的类型才能成为QVariant托管类型的一部分

//customtype.h
class CustomType {
};

Q_DECLARE_METATYPE(CustomType)
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过QVariant以下方式检索自定义类型:

CustomType ct = myVariant.value<CustomType>();
Run Code Online (Sandbox Code Playgroud)

这相当于:

CustomType ct = qvariant_cast<CustomType>(myVariant);
Run Code Online (Sandbox Code Playgroud)


lpa*_*app 18

您可以尝试使用qvariant_castqobject_cast.

QObject *object = qvariant_cast<QObject*>(selectItem);
Category *category = qobject_cast<Category*>(object);
Run Code Online (Sandbox Code Playgroud)

此外,永远不要将任何持久性语句放入Q_ASSERT.未启用断言时不会使用它.