Important: Please read the Qt Code of Conduct -

QML failing to detect QObject destroyed in C++

  • The presented code does the following:
    <1> Create object of QObject derived class and expose it to QML
    <2> The class has a pointer to another QObject derived class and the pointer is accessible to QML via Q_PROPERTY.
    <3> MouseArea in QML detects user-click and simply asks the c++ code for the pointer to be deleted.
    <4> Color of rectangle turns black once this is detected.

    The problem is that while certain approaches detect the deletion of the pointer by c++ other approaches don't.

    Look at the inline comments:
    Combination of (1) and (1b) works
    Combination of (1) and (1d) does not work
    (2) alone by itself works but (3) alone by itself does not.

    When things work you should see the color of the Rectangle turn to black from yellow.

    Can someone please explain this behaviour?

    CPP code:
    @class Name : public QObject
    Q_PROPERTY(bool boolVal READ boolVal CONSTANT FINAL)
    bool boolVal() const {return true;}

    class Root : public QObject
    QObject* name() const {return m_pName;}
    Q_INVOKABLE void deleteName() {delete m_pName; m_pName = 0;}
    Name *m_pName {new Name};

    //--- main
    int main(int argc, char *argv[])
    QGuiApplication app(argc, argv);

    Root objRoot;
    QtQuick2ApplicationViewer viewer0;
    viewer0.rootContext()->setContextProperty("objRoot", &objRoot);
    return app.exec&#40;&#41;;


    QML Code:
    @import QtQuick 2.0

    Rectangle {
    width: 360
    height: 360

    color: "red"
    Rectangle {
       id: objRect
       anchors {left: parent.left; top:}
       height: 70; width: 70;
       property bool checked
       property QtObject temp:
       color: checked ? "yellow" : "black"     //  (1)
       //color: objRect.temp && objRect.temp.boolVal ? "yellow" : "black"  //---&gt;WORKS (2)
       //color: && ? "yellow" : "black"  //---&gt;DOES NOT WORK !!! (3)
       Binding on checked {
          //value: objRect.temp && objRect.temp.boolVal //---&gt;DOES NOT WORK !!! (1a)
          //value: objRect.temp !== null && objRect.temp.boolVal //---&gt;WORKS (1b)
          value: objRect.temp ? objRect.temp.boolVal : false //---&gt;WORKS (1c)
          //Using directly without collecting in local QtQobject temp:
          //value: && //---&gt;DOES NOT WORK !!! (1d)
          //value: !== null && //---&gt;DOES NOT WORK !!! (1e)
          //value: ? : false //---&gt;DOES NOT WORK !!! (1f)
       Text {
           text: "Destroy"
           anchors.centerIn: parent
       MouseArea {
           anchors.fill: parent
           onClicked: objRoot.deleteName()


    Using : {Qt/QML 5.2.0, Win 7, MinGW 4.8, QtQuick 2.0}

  • Have you tried to use deleteLater()?

    Your example looks very wired to me.
    Deleting object in that way is a signed for bad design.

    What you also can do is connecting to the QObject::destroyed(...) signal in QML

Log in to reply