overloading qt properties

855 Views Asked by At

I've got a property of a custom type.

class foo : public QObject {
    Q_OBJECT
    Q_PROPERTY(Custom x READ x WRITE set_x)

public: 
    void set_x(Custom &x) { /*whatnot*/}
}

QJson effectively invokes the following dynamic assignment:

((QObject*)&foo_instance)->setProperty("x", QVariant(QString("something-from-json")))

which returns false, as documented in the Qt:

If the value is not compatible with the property's type, the property is not changed, and false is returned.

How can I shim this into my Custom value? Clearly defining a side-function void set_x(QString) or void set_x(QVariant) cannot possibly work, since the property system would be unaware of this accessor.

Also, where is the type compatibility checked? - the program control never reaches

int foo::qt_metacall(QMetaObject::Call _c, int _id, void **_a)

the function generated by the meta-object compiler..

How can I make Custom compatible with these types?

1

There are 1 best solutions below

2
On BEST ANSWER

It can be useful to read The Property System

Especially Properties and Custom Types part.

If to be brief, all properties save as QVariant.
You need to use Q_DECLARE_METATYPE macro to make your Custom type compatible with Qt properties.
And after that you have to call qRegisterMetaType function to register your type.