PDA

View Full Version : Use QVariant with custon data types



mcosta
11th January 2006, 12:00
Hi guys,

I need to use QVariant with custom data type (i.e. in QComboBox I can associate a box entry with data).
How can I do?

Thanks

Dusdan
11th January 2006, 12:16
from http://doc.trolltech.com/4.1/qvariant.html:

A Note on GUI Types
Because QVariant is part of the QtCore library, it cannot provide conversion functions to data types such as QColor, QImage, and QPixmap, which are part of QtGui. In other words, there is no toColor() function.
Instead, you can use the QVariant::value() or the qVariantValue() template function. For example:
QVariant variant;
...
QColor color = variant.value<QColor>();
The inverse conversion (e.g., from QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types:
QColor color = palette().background().color();
QVariant variant = color;

wysota
11th January 2006, 12:59
AFAIK you can't add custom datatypes to QVariant. You may only store custom data within one of the existing types (like a string or an int) like shown in the second post.

Dusdan
11th January 2006, 13:36
AFAIK you can't add custom datatypes to QVariant. You may only store custom data within one of the existing types (like a string or an int) like shown in the second post.you can store whatever you want, in fact QColor isn't supported natively (there's no toColor() method), because it's not part of QtCore.

you can use it this way:

MyType t;
QVariant var = t;
...
MyType t2 = var.value<MyType>();

mcosta
11th January 2006, 15:55
you can store whatever you want, in fact QColor isn't supported natively (there's no toColor() method), because it's not part of QtCore.

you can use it this way:

MyType t;
QVariant var = t;
...
MyType t2 = var.value<MyType>();

You can do this only for Registered types otherwise you obtain a compiler error
You can register a custom type in this way


Q_DECLARE_METATYPE(MyType);


If you want to register also a type name you can use


int myTypeId = qRegisterMetaType<MyType>("MyType")