How to include QVariant in a custom class?

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

I have a listview that I want to process with my elements by clicking on C ++ (I need to use C ++, not QML).

I can get the pointer path using the "connect" command, but I have a problem parsing QVariant into a user class;

Q_ASSERT(QObject::connect(list1, SIGNAL(triggered(QVariantList)), this, SLOT(openSheet(QVariantList)))); QVariant selectItem = m_categoriesListDataModel->data(indexPath); 

I tried using a static cast as shown below

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

but it returns:

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

Can someone help me with this?

+12
c ++ qt cascade qvariant blackberry-10
source share
2 answers

You can try using qvariant_cast and qobject_cast .

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

Also, never put a constant statement in Q_ASSERT. It will not be used if assert is not enabled.

+18
source share

UPDATE: works for a derived type other than QObject (see the answer to the final contest for this case)

First of all, you need to register your type in order to be part of the QVariant managed types.

 //customtype.h class CustomType { }; Q_DECLARE_METATYPE(CustomType) 

Then you can get your own type from QVariant as follows:

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

which is equivalent to:

 CustomType ct = qvariant_cast<CustomType>(myVariant); 
+18
source share

All Articles