1

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)?

Martin
  • 333
  • 1
  • 8

1 Answers1

0

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;
};
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • That's true, but that way I would not be able to use setProperty(...) to modify it. – Martin Mar 13 '20 at 17:41
  • 1
    @Martin Why is it necessary to use setProperty? – eyllanesc Mar 13 '20 at 17:45
  • I'am attempting to create a wrapper around generated QDBusAbstractInterface-derived class(it doesn't seem to support emiting "-Changed" signals for it's properties. I'am reimplementing the properties in the wrapper, and want to update them when the underlaying property changes(I get notification through different mechanism in the form of QMap ... "name"->"new value"). Because of that, I want to access the properties dynamicaly(to save on typing, less mistakes that way). – Martin Mar 13 '20 at 17:56
  • 1
    @Martin Why don't you make QDBusAbstractInterface a class C member and so you just expose those properties. I think you have an XY problem – eyllanesc Mar 13 '20 at 18:02
  • It's possible, I am basically trying to extend properties of existing class with a NOTIFY signal. (without modifying it's code as it is automatically generated) – Martin Mar 13 '20 at 19:43
  • 1
    Extension implies no hiding. So don't hide :) – Kuba hasn't forgotten Monica Mar 13 '20 at 20:05
  • Could you expand on that? – Martin Mar 15 '20 at 10:20