Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast a QVariant to custom class?

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

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

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

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 ?

like image 455
Mohamed Jihed Jaouadi Avatar asked Jun 23 '14 09:06

Mohamed Jihed Jaouadi


Video Answer


2 Answers

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);
like image 186
epsilon Avatar answered Sep 21 '22 18:09

epsilon


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.

like image 25
lpapp Avatar answered Sep 19 '22 18:09

lpapp