How to create read-only bindable properties?
Unsolved
Qt 6
-
I want to create bindable property that can be used in other properties' bindings, but which can be modified (and to which bindings can be set) only from inside of an object that owns it.
With Qt5 and using signals it can be done like this:
class Foo : public QObject { Q_OBJECT QML_ELEMENT Q_PROPERTY(int count READ count NOTIFY countChanged) public: int count() const { return mCount; } private: int mCount = 0; signals: void countChanged(); };
count
property can be observer outside ofFoo
by connecting to signal, but can only be changed from insideFoo
.I tried to do it with bindings instead of signals like this:
class Foo : public QObject { Q_OBJECT QML_ELEMENT Q_PROPERTY(int count READ count BINDABLE countBindable) public: int count() const { return mCount; } private: QBindable<int> countBindable() { return &mCount; } Q_OBJECT_BINDABLE_PROPERTY(Foo, int, mCount, nullptr) };
You can still observe
count
outside ofFoo
by creating bindings to it, however it can be modified outside by using QMetaProperty:auto foo = Foo(); auto meta = foo.metaObject(); auto prop = meta->property(meta->indexOfProperty("count")); prop.bindable(&foo).setBinding(Qt::makePropertyBinding([] { return 42; })); qInfo() << foo.count(); // Will print 42
It there any way to create a property in Qt6 that can be used in bindings but also can't be modified outside of its object?