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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24362946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:42:26  来源:igfitidea点击:

How can I cast a QVariant to custom class?

c++qtblackberry-10cascadeqvariant

提问by J.M.J

I'm developing a BlackBerry 10 mobile application using the Momentics IDE (native SDK).

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

I have a listview which I want to handle its items click with C++ (I need to use C++ not QML).

我有一个列表视图,我想用 C++ 处理它的项目点击(我需要使用 C++ 而不是 QML)。

I can get the index path using the "connect" instruction, but I have problem with parsing a QVariant to a custom class ;

我可以使用“connect”指令获取索引路径,但是我在将 QVariant 解析为自定义类时遇到问题;

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

QVariant selectItem = m_categoriesListDataModel->data(indexPath);

I tried to use the static cast like below

我尝试使用如下所示的静态转换

Category* custType = static_cast<Category*>(selectItem);

but it returns :

但它返回:

"invalid static_cast from type 'QVariant' to type 'Category*'"

Can anyone help me on this ?

谁可以帮我这个事 ?

回答by epsilon

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

编辑:适用于非 QObject 派生类型(请参阅 Final Contest 对此案例的回答)

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

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

//customtype.h
class CustomType {
};

Q_DECLARE_METATYPE(CustomType)

Then you can retrieve your custom type from QVariantin this way :

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

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

which is equivalent to:

这相当于:

CustomType ct = qvariant_cast<CustomType>(myVariant);

回答by lpapp

You could try using qvariant_castand qobject_cast.

您可以尝试使用qvariant_castqobject_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.

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