PDA

View Full Version : Convert between a custom data type wrapped in a QVariant



darkadept
16th March 2009, 22:34
I have a custom class called Money that I want stored in a QVariant. I then want to take that QVariant and convert it to and from a QVariant of type double.

Here is my custom Money class:


class Money {
public:
Money(double value = 0.00) {
_val = value;
}
~Money() { }
double toDouble() {
return _val;
}
operator Double() {
return toDouble();
}
private:
double _val;
};

Q_DECLARE_METATYPE(Money);


I'm using Qt's property system (which stores QVariants) but I'll just simplify everything here:


//Create a QVariant of type double
double myDouble = 2.345;
QVariant doubleVariant;
doubleVariant.setValue(myDouble);

//Create a QVariant of type Money
QVariant moneyVariant;
moneyVariant.setValue(Money(0.00));

/*This is where I'm bogged down.
I have a QVariant of type double that holds the real value.
I also have an empty QVariant of type Money.
I want to be able to transfer the value from doubleVariant to
moneyVariant without knowing about the Money class or double type.
I also want to preserve what type the destination QVariant is.*/

//Attempt to convert from the double variant to the money variant
moneyVariant = QVariant::fromValue(doubleVariant);
Money myMoneyValue = moneyVariant.value<Money>();

//Obviously the above two lines doesn't work.
//Instead of moneyVariant being a QVariant of type Money it is now
//a QVariant of type double. Also the conversion back to Money doesn't work.


Any ideas? I will try to clarify what I'm trying to do if that doesn't make sense.

Thanks,
Mike

wysota
16th March 2009, 23:25
I don't think this is possible. If your Money structure is equivalent to double, why not use double in the first place?

pckoster
17th March 2009, 09:07
Shouldn't you register it first with a call to qRegisterMetaType (http://doc.trolltech.com/4.1/qmetatype.html#qRegisterMetaType)

What are the results of calls to canConvert() and convert() or toDouble() functions?