Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. General talk
  3. Qt 6
  4. How to create read-only bindable properties?
Forum Updated to NodeBB v4.3 + New Features

How to create read-only bindable properties?

Scheduled Pinned Locked Moved Unsolved Qt 6
1 Posts 1 Posters 456 Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • E Offline
    E Offline
    equeim
    wrote on last edited by
    #1

    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 of Foo by connecting to signal, but can only be changed from inside Foo.

    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 of Foo 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?

    1 Reply Last reply
    1

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved