PDA

View Full Version : using custom datatypes with QVariant/Q_DECLARE_METATYPE();



SK.
12th December 2007, 12:12
Hello everyone,
I want to use a custom data type with QVariant, specifically I want to push_back a "Vector3" class instance onto a QVector<QVariant>. I already searched the forums and found some helpful information ( for example http://www.qtcentre.org/forum/f-qt-programming-2/t-use-qvariant-with-custon-data-types-146.html ), but somehow it doesn´t work the way it should.

my "Vector3" class:


#ifndef __VECTOR3_H_
#define __VECTOR3_H_

#include <QMetaType>

class Vector3
{

public:
Vector3(): x(0), y(0), z(0) {};

Vector3(float inX, float inY , float inZ) : x (inX), y (inY), z (inZ) {};


Vector3::Vector3(const Vector3 &vector3) {
x=vector3.getX();
y=vector3.getY();
z=vector3.getZ();
}

[...]

private:
float x;
float y;
float z;

};

Q_DECLARE_METATYPE(Vector3);

#endif //__VECTOR3_H_


I try to use it that way (parameters is: QVector<QVariant> parameters; ):


Vector3 test;
parameters.push_back(test);


Which results in the following:

.\view\Drawing.cpp(20) : error C2664: 'QVector<T>::push_back' : cannot convert parameter 1 from 'Vector3' to 'const QVariant &'
with
[
T=QVariant
]
Reason: cannot convert from 'Vector3' to 'const QVariant'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Now my naive understanding was that I´d only have to Q_DECLARE_METATYPE(Vector3) and everything would work, but that´s obviously wrong. A few pointers in the right direction would be greatly appreciated.

jpn
12th December 2007, 12:32
See article Using custom data types with Qt. You will have to use QVariant::fromValue() or to implement a QVariant() operator.

SK.
12th December 2007, 13:15
Thanks a lot, that did the trick. :)