The Qt docs contain this example:
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
public:
void setAuthor(const QString &a) {
if (a != m_author) {
m_author = a;
emit authorChanged();
}
}
QString author() const {
return m_author;
}
signals:
void authorChanged();
private:
QString m_author;
};
Is there a way to avoid writing all this boilerplate code just to define a QML-interoperable property? For example, since this code is calling the Q_PROPERTY macro anyway, can't this macro do the dirty work for me and define all the rest automatically?
Note: I've found a nice-looking set of macros here but it's not an official part of Qt, so I'm not sure if it's free of gotchas.
There is no standard solution for this, but then I looked on this issue while ago I found this, QmlTricks which I think is really nice implementation.
MEMBER is a way to go, but sometimes you might need more control of what's happening inside setter/getter methods, so to be honest I don't use it often.
I made my own subset with some additional macros like QObject's support for properties, custom setter/getter etc.