Problem regaridng Type casting QVariant
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.
Code:
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
Code:
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.
Re: Problem regaridng Type casting QVariant
Try using QVariant::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
Re: Problem regaridng Type casting QVariant
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.
Re: Problem regaridng Type casting QVariant
Quote:
Originally Posted by
sudheer168
But here I am using a structure district which was not derived from any class.
Anyway, did you try my suggestion?
Re: Problem regaridng Type casting QVariant
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:
Code:
Q_DECLARE_METATYPE(District *)
Then you can use the following to set the value in a QVariant instance:
Code:
District *d = ...
qVariantFromValue(d)
Then you can get the value from the QVariant instance:
Code:
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.
Re: Problem regaridng Type casting QVariant
Hi ,
Thanks for all your replies. I got the solution.
Regards,
Sudheer.