[SOLVED]Binding between C++ object and Listview delegate
-
Hi everyone,
I come back again with an issue when trying to bind between properties of a C++ object and qml properties.
Here is the situation
MyCppObject.h:
@
class MyCppObject
{
Q_PROPERTY( QString name READ name WRITE setName NOTIFY nameChanged )public:
MyCppObject( QObject* parent = nullptr,
QString name = "Unknown" );QString name(){ return _name }; void setName( QString name ){ _name = name; emit( nameChanged() ) };
signals:
void nameChanged();
private:
QString _name;
}@This object is registered in the main using qmlRegisterType.
Multiple objects of class MyCppObject are inserted in a custom QAbstractListModel and this list is used as a model for a ListView in qml with a delegate as followed:
@
Component
{
id: mydelegate
Text
{
height: cellHeight
width: listView.width
text: model.name
}
}@This works perfectly but whenever names are updated in C++ they are not in qml.
I looked towards doing some Binding and so my delegate looks like this :@
Component
{
id: mydelegate
Text
{
id: mydelegateText
height: cellHeight
width: listView.width
Binding
{
target: mydelegateText
property: "text"
value: model.name
}
}
}@I have the same result as before, meaning that the default name is well displayed but whenever it is updated there is no update on the qml side
-
Fix: emit dataChanged() in your C++ model.
As per your component code you are using models probably in a Listview. So emitting changed signal while updating name will not update the name in the delegate as you not emitting dataChanged() in the model.
Doing so will tell the connected views to update the items at index for which the dataChanged is emitted and fetch the data again, thus updating the name. -
Sorry for the late answer, I got back to my code and it does work with your fix. Thanks