【问题标题】:How to cast QVariant to custom class?如何将 QVariant 转换为自定义类?
【发布时间】:2010-09-26 02:30:47
【问题描述】:

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

【问题讨论】:

    标签: c++ linux qt casting


    【解决方案1】:

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

    【讨论】:

    • Q_DECLARE_METATYPE 是否必须在类/命名空间定义之外?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多