【问题标题】:Setting property in QObject not working for custom type. Can you tell me why?QObject 中的设置属性不适用于自定义类型。你能告诉我为什么吗?
【发布时间】:2020-11-24 12:39:48
【问题描述】:

我正在尝试使用自定义类型 MoneyTst 作为类 tst 中的属性,这是一个 qobject。当我在 tst 实例上调用方法 setProperty(amount,8000) 时,它不会将值分配给属性。你能解释一下为什么这不是在这个属性上设置它的值吗?

//我正在尝试使用QObject.setProperty()设置的自定义类型

struct MoneyTst{

    MoneyTst(){}
    MoneyTst(int value){
        this->value = value;
    }

    int value;
    int getValue() const{
        return this->value;
    }

    void registerConverter(){
        QMetaType::registerConverter(&MoneyTst::getValue);
    }
};
Q_DECLARE_METATYPE(MoneyTst)

class tst : public QObject{
    Q_OBJECT
//Using MoneyTst over here as property
    Q_PROPERTY(MoneyTst amount READ getAmount WRITE setAmount)

public:
    MoneyTst getAmount() const{
        return this->amount;
    }

    void setAmount(MoneyTst value){
        this->amount = value;
    }
private:
    MoneyTst amount;
};



void runTest{
    tst o;
    o.setProperty("amount",8000);
    QVERIFY(o.property("amount").toInt() == 8000); //Fails because not value is not setting to 8000.

}

【问题讨论】:

    标签: qt qobject qmetatype


    【解决方案1】:

    问题出在这两行:

    o.setProperty("amount",8000);
    QVERIFY(o.property("amount").toInt() == 8000);
    

    首先,您从一个 int 创建一个 QVariant 并且您的属性函数,它使用 MoneyTst 甚至没有被调用。 然后您尝试将 MoneyTst 类型(存储在 QVariant 中)转换为 int,但失败了。 基于 QVariant 的属性系统需要对自定义类型进行显式类型转换。

    你应该这样改变你的代码:

    o.setProperty("amount", QVariant::fromValue(MonetTst{8000}));
    QVERIFY(o.property("amount").value<MoneyTst>().getValue() == 8000);
    

    【讨论】:

      【解决方案2】:

      让你的结构成为一个 Q_GADGET,像这样:

      struct MoneyTst{
          Q_GADGET
          
          MoneyTst(){}
          ...
      };
      Q_DECLARE_METATYPE(MoneyTst)
      

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2013-12-16
        • 2016-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多