PDA

View Full Version : how to set custom type data to a QTreeWidgetItem?



qlands
4th July 2011, 14:52
Hi,

How can I set the data of a QTreeWidgetItem with a custom type?

I can, for example, declare my type with:



struct CntyData {
QString Code;
QString Desc;
QString Desc2;
QString Desc3;
QString Desc4;
QString Status;
};
typedef CntyData TCntyData;
Q_DECLARE_METATYPE(TCntyData);


Then assign the custom data with:


TCntyData s;
QVariant var;
var.setValue(s);

item->setData(0,Qt::UserRole,var);



But how can I do this without creating QVariant var and just passing s to setData.

I tried:



TCntyData s;
item->setData(0,Qt::UserRole,QVariant(s));


But it get the error: no matching function for call to 'QVariant::QVariant(TCntyData&)'

Thanks

mcosta
4th July 2011, 14:59
Read here.

You nedd to write:

a public default constructor,
a public copy constructor
a public destructor.

stampede
4th July 2011, 16:28
You nedd to write:
a public default constructor,
a public copy constructor
a public destructor.
Structures have all mentioned above provided by default by the compiler.
Your problem is that there is no constructor in QVariant class that takes your custom structure as an argument, you can use for example the template methods for conversions:


struct struct_test{
QString str;
int val;
// ...
};
Q_DECLARE_METATYPE(struct_test);

int main(int argc, char *argv[])
{
struct_test s; s.str = "hello";
QMap<int,QVariant> map;
map[0] = qVariantFromValue<struct_test>(s);
qDebug() << qVariantValue<struct_test>(map[0]).str;
}

read here for details and examples : custom type example (http://doc.qt.nokia.com/latest/tools-customtype.html)