PDA

View Full Version : Storing and reading back template types in QVariant



Daniel Dekkers
1st April 2010, 16:46
Hi,

The strangest thing...

I'm filling QListWidgetItems with a template type T* p_Object (i've added the Q_DECLARE_METATYPE() macro to the candidate classes for T). Amazingly, it works fine, i was pleasantly surprised: after storing T* as a Qt::UserRole, i immediately read back the data to check, and there are no problems.

But... reading the data back in a later pass (using the same ItemToObject() function), it fails. The QVariant seems ok (has the same id number) but the qVariantValue<T*> "cast" fails. I'm not changing anything in the QListWidgetItems inbetween passes...

Any idea's?

Kind Regards,
Daniel Dekkers



template <class T>
void
c_ListViewController<T>::SetItemData(QListWidgetItem* p_Item, T* p_Object)
{
p_Item->setData(Qt::DisplayRole, QString::fromStdWString(p_Object->Name()));

QVariant l_Data;
l_Data.setValue(p_Object);
p_Item->setData(Qt::UserRole, l_Data);

// Check...
T* l_ReadBackObject = GetItemData(p_Item);
if (p_Object!=l_ReadBackObject)
{
c_MessageDialog* l_MessageDialog = new c_MessageDialog(this, "Something wrong..."); l_MessageDialog->exec();
}
}

// ================================================== ===========================

template <class T>
T*
c_ListViewController<T>::GetItemData(QListWidgetItem* p_Item) const
{
T* l_ReadBackObject = NULL;
QVariant l_ReadBackData = p_Item->data(Qt::UserRole);
l_ReadBackObject = qVariantValue<T*>(l_ReadBackData);
return l_ReadBackObject;
}

foxyproxy
5th April 2010, 08:40
I use for storing a value qVariantFromValue(myValue) and to get it back variant.value<MyCustomValue>(). Have your tried them?