PDA

View Full Version : Problem regaridng Type casting QVariant



sudheer168
2nd November 2009, 05:27
Hi everybody ,
I got problem regarding typecasting . I have one structure called Disrict and I want to set the object of district as data to Qtreewidgetitem.




QTreeWidgetItem *itemdist = new QTreeWidgetItem();
District *dist;
itemdist->setData(1, Qt::ToolTipRole, dist);
QVariant item = itemdist->data(1, Qt::ToolTipRole);
district *temp = static_cast<district*>(temp1);



But in line 5 it is showing error as




error C2440: 'static_cast' : cannot convert from 'QVariant' to 'district *'



I tried by using reinterpret_cast ,but it is showing same error . so how can I cast the variant item to district type. The main thing I want to do is assing district object to Qtreewidgetitem object and I want to get back the district object using Qtreewidgetitem object.
So please suggest me to solve this problem.

Regards,
Sudheer.

montuno
2nd November 2009, 08:27
Try using QVariant::setValue(..) (http://qt.nokia.com/doc/4.5/qvariant.html#setValue) for example:

// set
QWidget* widget = ui.MyWidget->window();

QVariant var;
var.setValue(widget);
listWidgetItem->setData(Qt::UserRole, var);

// get
QVariant var = item->data(Qt::UserRole);
QWidget* widget= var.value<QWidget*>();


I'm not completely sure, but so far I know you only can use this for classes inherited by QObject...

Montuno

sudheer168
2nd November 2009, 08:42
Hi thanks for your kind reply. But here I am using a structure district which was not derived from any class.
So what I have to do to solve my problem .
Please help me to solve this problem.

regards,
sudheer.

montuno
2nd November 2009, 15:17
But here I am using a structure district which was not derived from any class.

Anyway, did you try my suggestion?

smacchia
2nd November 2009, 15:28
Your structure, class, or pointer need not be derived from any other class. You can use QVariant to hold any kind of object. First you need to use the Q_DECLARE_METATYPE macro in a header file:

Q_DECLARE_METATYPE(District *)

Then you can use the following to set the value in a QVariant instance:


District *d = ...
qVariantFromValue(d)

Then you can get the value from the QVariant instance:

QVariant item = itemdist->data(1, Qt::ToolTipRole);
District *d = item.value<District *>();

Also - look at the description of the QVariant class in the documentation - it should show you how to deal with custom structures, etc.

sudheer168
3rd November 2009, 06:02
Hi ,
Thanks for all your replies. I got the solution.

Regards,
Sudheer.