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.
You can avoid the implementation of accessor functions if you use
MEMBERproperties. Then you only need the member and the optional notify signal.The macro approach should work fine, however there are two problems with the one you have linked:
So using
MEMBERyou can simplify it further:And then just: