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_OBJECT
Q_PROPERTY(bool boolVal READ boolVal CONSTANT FINAL)
public:
bool boolVal() const {return true;}
};class Root : public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* name READ name CONSTANT FINAL)
public:
QObject* name() const {return m_pName;}
Q_INVOKABLE void deleteName() {delete m_pName; m_pName = 0;}
private:
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); viewer0.setMainQmlFile(QStringLiteral("qml/dualWindowApp/main.qml")); viewer0.showExpanded(); return app.exec();
}@
QML Code:
@import QtQuick 2.0Rectangle {
width: 360
height: 360color: "red" Rectangle { id: objRect anchors {left: parent.left; top: parent.top} height: 70; width: 70; property bool checked property QtObject temp: objRoot.name color: checked ? "yellow" : "black" // (1) //color: objRect.temp && objRect.temp.boolVal ? "yellow" : "black" //--->WORKS (2) //color: objRoot.name && objRoot.name.boolVal ? "yellow" : "black" //--->DOES NOT WORK !!! (3) Binding on checked { //value: objRect.temp && objRect.temp.boolVal //--->DOES NOT WORK !!! (1a) //value: objRect.temp !== null && objRect.temp.boolVal //--->WORKS (1b) value: objRect.temp ? objRect.temp.boolVal : false //--->WORKS (1c) //Using directly without collecting in local QtQobject temp: //---------------------------------------------------------- //value: objRoot.name && objRoot.name.boolVal //--->DOES NOT WORK !!! (1d) //value: objRoot.name !== null && objRoot.name.boolVal //--->DOES NOT WORK !!! (1e) //value: objRoot.name ? objRoot.name.boolVal : false //--->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