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

Gia*_*rlo 2 c++ linux qt casting

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

sho*_*osh 6

你需要在.h文件中的某个地方声明如下:

Q_DECLARE_METATYPE(MyStruct)
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

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

// retrieve the value
MyStruct s2 = var.value<MyStruct>();
Run Code Online (Sandbox Code Playgroud)

看到这里的文档