c++qtqmlqt-quickqproperty

Q_PROPERTY with private setter


I have an QObject with properties accessible from QML. Something like:

Class C : public QObject {
Q_OBJECT
public:
explicit C(QObject * parent = nullptr);
Q_PROPERTY(QString ro_text READ ro_text WRITE setRo_text NOTIFY ro_textChanged)
};

Is it possible to make the setter(setRo_text) "private", so the property cannot by modified from QML, but can still be set from C++ code(inside the class)?


Solution

  • if you don't want it to be modified from QML then don't declare the WRITE, and create a method that every time the property changes it emits the signal, the setter method can be public or private but it can't be accessed in QML

    class C: public QObject{
        Q_OBJECT
        Q_PROPERTY(QString ro_text READ ro_text NOTIFY ro_textChanged)
    public:
        C(QObject *parent=nullptr): QObject(parent){
    
        }
        QString ro_text() const {
            return m_ro_text;
        }
    Q_SIGNALS:
        void ro_textChanged();
    private:
        void setRo_text(const QString & text){
            if(m_ro_text == text)
                return;
            m_ro_text = text;
            Q_EMIT ro_textChanged();
        }
        QString m_ro_text;
    };