16

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 ?

lpapp
  • 47,035
  • 38
  • 95
  • 127
J.M.J
  • 1,081
  • 3
  • 18
  • 35

2 Answers2

24

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);
epsilon
  • 2,604
  • 12
  • 21
  • Thank you for your help. I tried to put the "Q_DECLARE_METATYPE" instruction like you describe but it returns an error "within this context", I think thats because my custom type inherits from the QOBject class : "class Category: public QObject" – J.M.J Jun 23 '14 at 10:23
  • @FinalContest is right. Question does not mention your were treating a QObject derived type. – epsilon Jun 23 '14 at 10:35
  • 1
    Your comment helped me out a lot, I feel like yours should be the answer, and that ldapps should be an answer to an entirely different question, as J.M.J didn't specify they were deriving from QObject in the original post – Krupip May 11 '17 at 19:49
22

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.

lpapp
  • 47,035
  • 38
  • 95
  • 127
  • 1
    thanks for the information. About "Q_DECLARE_METATYPE", I tried to put it in the class definition like this [example](http://blackberry.github.io/Qt2Cascades-Samples/docs/threads-queuedcustomtype-src-block-hpp.html) but it doesn't work; it returns "within this context" (I think this is because the class is a QObject one "class Category: public QObject") and when I try to put it wherever outisde the class definition it returns "a template declaration cannot appear at block scope". – J.M.J Jun 23 '14 at 10:17