How to notify QML item that its property has changed?

11,537

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)
}
Share:
11,537
laurent
Author by

laurent

Updated on July 09, 2022

Comments

  • laurent
    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 &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?

  • Kevin Krammer
    Kevin Krammer over 7 years
    Also, if you make "title" a property on your QmlNote class, you can just use note.title in any property binding and it will get re-read when you emit that property's change signal
  • dtech
    dtech over 7 years
    I 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.