C++ 如何将QVariant强制转换为自定义类?

C++ 如何将QVariant强制转换为自定义类?,c++,linux,qt,casting,C++,Linux,Qt,Casting,我在QTreeWidgetItem中有一个QVariant对象,如何将其强制转换到我自己的对象 您需要在.h文件中声明以下内容: Q_DECLARE_METATYPE(MyStruct) 然后你可以使用: MyStruct s; QVariant var; var.setValue(s); // copy s into the variant // retrieve the value MyStruct s2 = var.value<MyStruct>(); MyStruct;

我在QTreeWidgetItem中有一个QVariant对象,如何将其强制转换到我自己的对象

您需要在
.h
文件中声明以下内容:

Q_DECLARE_METATYPE(MyStruct)
然后你可以使用:

MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant

// retrieve the value
MyStruct s2 = var.value<MyStruct>();
MyStruct;
qvar;
变量设置值;//将s复制到变体中
//检索值
MyStruct s2=变量值();