PDA

View Full Version : Q_DECLARE_METATYPE and qVariantCanConvert



manojmka
31st March 2008, 10:49
Hi,

I have the following class in a static lib:



class ITGraphic : public QPixmap
{
....
....
};

Q_DECLARE_METATYPE(ITGraphic);


Thereafter I am returning ITGraphic object in another static library from model class in data function:



QVariant ITPictureList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();

if (role == Qt::DecorationRole)
{
ITGraphic *graphic = GetBitmap(index.row());
if(graphic != NULL)
{
QPixmap tmpPixmap = graphic->scaled(iconSize,Qt::KeepAspectRatio);
return QIcon(tmpPixmap);
}
else
return QVariant();
}
else if (role == Qt::UserRole)
{
return *(GetBitmap(index.row()));
}

return QVariant();
}


I am trying to get this object like this:

QVariant value = picList->data(index,Qt::UserRole);



res = qVariantCanConvert<ITGraphic>(value);
ITGraphic pGraphic = qvariant_cast<ITGraphic>(value);


qVariantCanConvert returns false here and I am not able to get the proper object here. But if I try the following, it works:



QPixmap pGraphic = qVariantValue<QPixmap>(picList->data(index, Qt::UserRole));



Can someone help me, how to get the ITGraphic object here?

Regards,
Manoj

manojmka
1st April 2008, 07:13
I finally found the solution to this myself. There are two possible solutions to this:

(1) Implementing a copy constructor for ITGraphic class and then it should start work.

(2) I did it other way round and changed the data function as follows:


QVariant ITPictureList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();

if (role == Qt::DecorationRole)
{
ITGraphic *graphic = GetBitmap(index.row());
if(graphic != NULL)
{
QPixmap tmpPixmap = graphic->scaled(iconSize,Qt::KeepAspectRatio);
return QIcon(tmpPixmap);
}
else
return QVariant();
}
else if(role == Qt::DisplayRole)
return GetFileName(index.row());
else if (role == Qt::UserRole)
{
ITGraphic *graphic = GetBitmap(index.row());
QVariant v;
qVariantSetValue(v,graphic);
return v;
}
else if (role == Qt::ToolTipRole)
return GetFilePathName(index.row());

return QVariant();
}


Then getting the data like this:



ITGraphic *pGraphic = qVariantValue<ITGraphic*>(picList->data(index,Qt::UserRole));


It works!! :-)

Regards,
Manoj