How to notify QML item that its property has changed?
The signal will emit only if the actual object has changed, that is, a different object is assigned to the property. In your case it will always be the same object. Furthermore, you haven't really assigned anything to the property. If you already have exposed the object as a context property then that's all you need.
You can simply implement a signal noteChanged()
and emit it on every reload in C++. The on the qml side, you can use a Connections
element to implement a handler for it.
Connections {
target: qmlNote
onNoteChanged: console.info(qmlNote.title)
}
laurent
Updated on July 09, 2022Comments
-
laurent almost 2 years
I've got a QObject that wraps another plain object:
#include "qmlnote.h" QString QmlNote::title() const { return note_.title(); } void QmlNote::reload(const Note ¬e) { note_ = note; }
which I load in QML using this:
ctxt->setContextProperty("note", &qmlNote);
and later on I make it wrap a different note:
qmlNote.reload(newNote);
Then in QML, I want to do something when this note change:
import QtQuick 2.0 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.1 Item { property QtObject note onNoteChanged: { console.info(note.title) } }
I would like
onModelChanged()
to be triggered whenever I callreload()
however it's not happening. I guess I would need to emit some signals from somewhere to notify the QML view that the note has changed, but not sure where. I thought I could emit a signal fromreload()
but it seemsQObject
doesn't have a built-inchanged
signal.Any suggestion on how to handle this?
-
Kevin Krammer over 7 yearsAlso, if you make "title" a property on your
QmlNote
class, you can just usenote.title
in any property binding and it will get re-read when you emit that property's change signal -
dtech over 7 yearsI would have suggested that, but the example code does not use it in a binding. Implementing a proper property is a good idea it most of the cases.