Qt Meta Type

The QMetaType class manages named types in the meta-object system

The class is used as a helper to marshall types in QVariant and in queued signals and slots connections. It associates a type name to a type so that it can be created and destructed dynamically at run-time. Declare new types with Q_DECLARE_METATYPE() to make them available to QVariant and other template-based functions. Call qRegisterMetaType() to make types available to non-template based functions, such as the queued signal and slot connections.

Q_DECLARE_METATYPE(MyStruct)
MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant
// retrieve the value
MyStruct s2 = var.value<MyStruct>();

what can you do once you register type with meta types?

  • create object with type id
  • value as Qvariant
  • streaming data of object (save ,load ,<<,>>,…)(qRegisterMetaTypeStreamOperators<type>(type_name))
  • pass values betweens queued signals and slots connections

struct Test2
{
    int i;
};
Q_DECLARE_METATYPE(Test2);

QDataStream &operator<<(QDataStream &out, const Test2 &myObj)
{
    out<<myObj.i;
    return out;
}

QDataStream &operator>>(QDataStream &in, Test2 &myObj)
{
    in>>myObj.i;
    return in;
}

qRegisterMetaTypeStreamOperators<Test2>("Test2");

QVariant var1;
Test2 t1{.i=45};
var1.setValue(t1);
QFile f("./hello.txt");
f.open(QIODevice::WriteOnly);
QDataStream ds(&f);
ds<<var1;
f.close();

QVariant var2;
Test2 t2;
var2.setValue(t2);
f.open(QIODevice::ReadOnly);
ds>>var2;
f.close();
 qDebug()<<"value is : "<<var2.value<Test2>().i;//45
qMetaTypeId<type>()//return type id of type
QMetaType::fromType<type>()//return QMetaType 
QMetaType::type("Test2");//return type id by type name

or you can use member functions

QMetaObject* metaObject();// if it subclass of QObject return meta object
void* create(const void *copy = 0)// return pointer for copy of copy
void* construct(void *where, const void *copy = 0)// create copy of copy with determined adress (where)
destroy(void*)//
destruct(int type,void* where)// call destruct function without delete operator

QVariant

//before you can use any type as variant you sould to use Q_DECLARE_METATYPE
qvariant_cast<Type>(variant);//cast variant to type
variant.value<Type>();//cast value to type