通过QQmlContext::setContextProperty注册C++的对象实例至qml中,对象提前被析构
原因:仔细看QQmlContext::setContextProperty的说明,专门强调了
QQmlContext does not take ownership of value.
对象实例的生命期需要我们自己管理,所以对象需要在堆上创建,否则离开了当前作用域就被析构了
//CMyObject.hpp
CMyObject: public QObject
{
Q_OBJECT
public:
CMyObject(const QString &name, QObject *parent= nullptr): QObject(parent)
{
m_Name = name;
qDebug() << "CMyObject "<<m_Name<<" construct";
}
~CMyObject()
{
qDebug() << "CMyObject "<<m_Name<<" destroy";
}
private:
QString m_Name;
}
//main.cpp
int main(int argc, char *argv[])
{
...
QQmlApplicationEngine engine;
CMyObject mObj("stack");
CMyObject *pObj = new CMyObject("heap");
engine.rootContext()->setContextProperty("stack_obj", &mObj);
engine.rootContext()->setContextProperty("heap_obj", pObj);
...
return app.exec();
}
在栈上分配的对象“mObj”将在"return app.exec()"之后不久析构,打印“CMyObject stack destroy”,而“CMyObject heap destroy”将不会被打印