如何将QVariant转换为自定义类?

时间:2008-12-09 18:07:57

标签: c++ linux qt casting

我在QTreeWidgetItem中有一个QVariant对象,如何将它转换为我自己的对象?

1 个答案:

答案 0 :(得分:6)

您需要在.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>();

see the docs here