A way to avoid boilerplate code for defining QObject properties in C++ (to be accessible from QML)?



  • 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.


  • Lifetime Qt Champion

    Hi,

    Take a look at the MEMBER element of the Q_PROPERTY declaration here.

    It likely does what you want.

    Hope it helps


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.