Exposing object from C++ to qml returns null



  • Hello, I'm playing with qml and I'm trying to build a small program based on this documentation http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html where you can set properties and methods from c++ to qml.

    So... my problem is that is partially working.
    I'm sending the msg object to qml. Here is my qml code:

    @import QtQuick 2.0

    Rectangle {
    width: 250
    height: 100
    color : "#e5f3fe"
    border.color: "#114273"

    Component.onCompleted: {
        msg.author = "Jonah"  // invokes Message::setAuthor()
    }
    
    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log("msg= "+msg);  // this returns msg=null
    

    // var result = msg.postMessage("Hello from QML")
    // console.log("Result of postMessage():", result)
    // msg.refresh();
    }
    }
    }@

    So... when I set @msg.author = "Jonah"@ everything works great, the setAuthor method is called, however when I click on mouse area the msg is null.

    Do you know why and how can I fix this?

    Thanks


  • Moderators

    Hi,

    Is it the same example that you are trying from that doc as it is? It works for me. Which Qt Version/OS ?



  • Hello, p3c0. Thanks for your reply.
    Qt 5.4, WIndows 7, MSVC 2013

    I tried to shrink my problem to a very simple program. I have a NotificationWindow that extends QWidget , and in that constructor I create a QQuickWidget attached to the NotificationWindow.
    The qml is rendered ok, the passed object is ok in Component.onCompleted but not on MouseArea.

    I'll attach the program source code to see what seems to be the problem.

    Download the program: QtQuickTest : https://app.box.com/s/5fg2hyh5y5sst4pxc4mu7aedex2g6hrj

    Thanks


  • Moderators

    That is because MessageBoard object which is created on stack in NotificationWindow constructor dies when the constructor exits. Create that object on heap instead, using new.



  • Thanks. That was the problem. Now is working great.


  • Moderators

    Glad that its working :)
    Don't forget to delete that object or there would be a memory leak. Since it is in NotificationWindow widget you can pass it as a parent using this to MessageBoard so that when NotificationWindow gets deleted so does MessageBoard gets too.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.