4

I am writing a Qt app that maps a C++ class to Javascript object in QtWebkit. Firstly let me explain what I am trying to do:

I have a class inherited from QObject:

class myobj : public QObject {
    Q_OBJECT
public:
    myobj();
    ~myobj();

pulbic slots:
    void getData();
}

And in another class I tried to add myobj instances to QVariantMap:

QVariantMap anotherClass::getObj() {
    myobj* obj1 = new myobj();
    myobj* obj2 = new myobj();

    QVariantMap items;

    items.insert(QString("0"), QVariant(*obj1));
    items.insert(QString("1"), QVariant(*obj2));

    return items;
}

And then I got the following error:

error: no matching function for call to ‘QVariant::QVariant(myobj&)’

So I tried to add declarations:

Q_DECLARE_METATYPE(myobj);

But I got:

error: ‘QObject::QObject(const QObject&)’ is private

Any idea about this?

Mickey Shine
  • 12,187
  • 25
  • 96
  • 148

2 Answers2

3

Like the compiler said, no constructor of QVariant exists that take a myobj as parameter. Have you tried to use the qVariantFromValue function instead?

I think this is what you are searching for.

Patrice Bernassola
  • 14,136
  • 6
  • 46
  • 59
  • I also tried this: http://stackoverflow.com/questions/956335/subclass-of-qobject-qregistermetatype-and-the-private-copy-constructor but seemd still could not work – Mickey Shine Nov 29 '10 at 13:28
  • 1
    As explains here (http://doc.trolltech.com/4.7/qmetatype.html#Q_DECLARE_METATYPE) you have to declare a public default constructor, a public copy constructor and a public destructor. You do not have any copy constructor. So compiler tries to use the one of the mother class (QObject) which has been declared as private – Patrice Bernassola Nov 29 '10 at 13:57
  • 2
    QObjects and QVariant doesn't go together well, as variant _values_ are supposed to be copied, while QObjects are not. – Frank Osterfeld Nov 29 '10 at 14:15
  • The example in the description of the qVariantFromValue function is done with a QObject. So I guess it's not a problem – Patrice Bernassola Nov 29 '10 at 14:20
2

If you register your custom type with Q_DECLARE_METATYPE(myobj), your class needs a public default constuctor (ok), a public destructor (ok) and a public copy constructor (MISSING which the error message is telling you), see the documentation.

hmuelner
  • 8,093
  • 1
  • 28
  • 39