Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to notify QML item that its property has changed?

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 &note) {
    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 call reload() 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 from reload() but it seems QObject doesn't have a built-in changed signal.

Any suggestion on how to handle this?

like image 543
laurent Avatar asked Feb 06 '23 12:02

laurent


1 Answers

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)
}
like image 137
dtech Avatar answered Feb 08 '23 16:02

dtech