Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a property binding in Qt/C++?

Tags:

c++

qt

qml

In QML, it's easy write create a property binding, such as:

Rectangle {
    width: parent.width
} 

Is it possible to do this in C++ too?

like image 637
Zen Avatar asked Sep 29 '15 11:09

Zen


People also ask

What is property binding in Qt?

Property bindings are a core feature of QML that lets developers specify relationships between different object properties. When a property's dependencies change in value, the property is automatically updated according to the specified relationship.

What is binding in QML?

Binding to an Inaccessible Property Sometimes it is necessary to bind an object's property to that of another object that isn't directly instantiated by QML, such as a property of a class exported to QML by C++. You can use the Binding type to establish this dependency; binding any value to any object's property.

What is Q_PROPERTY in QML?

Exposing Properties. A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived or Q_GADGET class are accessible from QML.


2 Answers

In Qt, some QObjects have certain properties that can be "bound" using signals and slots:

auto *someWidget = QPushButton(/* ... */);
auto *otherRelatedWidget = QLabel( /* ... */ );
// windowTitle is a property for both QWidgets
QObject::connect(someWidget, &QWidget::windowTitleChanged,
                 otherRelatedWidget, &QWidget::setWindowTitle);

Apart from this, you can still connect other signals and slots, even if they're not associated to properties.

I've got to point out that there is no syntax sugar for doing this. See the properties documentation for more info.

like image 84
Felipe Lema Avatar answered Oct 13 '22 06:10

Felipe Lema


In Qt6 you can use QProperty to achieve c++ property bindings.

Check out this blog post: https://www.qt.io/blog/property-bindings-in-qt-6

They're slightly different than QML binding since they execute lazily. QML binding execute eagerly on every signal. Under the hood QProperty uses thread local storage (TLS) to keep track of dependancies while executing value(). It's definitely an interesting piece of technology and adds a declarative programming paradigm to c++.

like image 2
vpicaver Avatar answered Oct 13 '22 07:10

vpicaver