i am trying to use a custom type MoneyTst as a property in the class tst, which is a qobject. When i invoke the method setProperty(amount,8000) on a tst instance, it is not assigning the value to the property. Can you explain why this is not setting its value on this property ?
//Custom Type I am trying to set with 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.
}
The problem is in these two lines:
First you create a QVariant from an int and your property function, which takes MoneyTst is not even called. Then you try to convert MoneyTst type (stored in QVariant) to an int, which fails. The property system based on QVariant demands explicit type conversion for custom types.
You should change your code this way: