[Interest] How to create read-only bindable properties?

Alexey Rochev equeim at gmail.com
Sun Dec 13 14:22:13 CET 2020


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 signals, you would do it by creating property with NOTIFY
signal but without WRITE setter. This way you can observe property,
but not modify it.
I tried to do it with bindable properties like this:

class Foo : public QObject {
    Q_OBJECT
    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)
};

However, you can still modify it by setting binding on it using QMetaObject:

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?


More information about the Interest mailing list