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

Lars Knoll lars.knoll at qt.io
Mon Dec 14 09:26:02 CET 2020


On 13 Dec 2020, at 14:22, Alexey Rochev <equeim at gmail.com<mailto:equeim at gmail.com>> wrote:

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?

We’re lacking that currently. Let’s try to add something for Qt 6.1. I’ve created https://bugreports.qt.io/browse/QTBUG-89469 to track it.

Cheers,
Lars

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20201214/d76fde69/attachment.html>


More information about the Interest mailing list