Setting property in QObject not working for custom type. Can you tell me why?

763 views Asked by At

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.

}
2

There are 2 answers

0
Vasilij On

The problem is in these two lines:

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

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:

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

Make your struct a Q_GADGET, like this:

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