Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind C++ property to QML property?

Tags:

c++

qt

qobject

qml

So I know how to bind QML property to C++ property, so when C++ one calls notify signal, QML updates the view. Is there any way to make C++ property update when user changes something using UI?

For example, I have a Combobox, and I want some C++ property to be updated when user changes value of combobox.

EDIT: By C++ properties I mean Q_PROPERTY macro in QObject-derived classes.

like image 364
Rinat Veliakhmedov Avatar asked Jan 11 '17 12:01

Rinat Veliakhmedov


People also ask

What is property binding in QML?

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.

How do you use property in QML?

A property is an attribute of an object that can be assigned a static value or bound to a dynamic expression. A property's value can be read by other objects. Generally it can also be modified by another object, unless a particular QML type has explicitly disallowed this for a specific property.

How do I change the properties of QML in C++?

You should always use QObject::setProperty(), QQmlProperty or QMetaProperty::write() to change a QML property value, to ensure the QML engine is made aware of the property change.


2 Answers

To bind a property from an object you didn't create in QML (or was created in another context), you have to use Binding. In your case :

Binding {
    target: yourCppObject
    property: "cppPropertyName"
    value: yourComboBox.currentText
}
like image 107
GrecKo Avatar answered Oct 13 '22 18:10

GrecKo


Perhaps an answer to a similar question would be helpful.

It shows how to connect the standard (not custom) qml property with something in C++.

like image 20
ZolotovPavel Avatar answered Oct 13 '22 18:10

ZolotovPavel