Qt那些事0.0.28 之 QML中的C++对象

今天脱了个坑,很大的坑。

C++代码中建立的类,在QML通过Q_INVOKABLE的函数获取此类一个对象的指针,作为一个Repeater的model。

如:

Column{
    Repeater{
        model:$core.getModel(0)
        delegate:Rectangle{}
    }
}
class Model:public QAbstractListModel{

} 
class Core:public QObject{
public:
    Core(QObject* parent = nullptr):QObject(parent){
        for(int i = 0;i < 4;i++){
            m_models.append(new Model);
        }   
    }
    Model* getModel(int index){return m_models.at(index);}
private:
    QList<Model*> m_models;    
}

测试程序运行没有问题,可移植到主程序就崩溃。最后测试出为m_models中的对象被释放(增加析构函数后打印消息)。

猜测是构造Model时没有指定父对象,测试修改Model,将Core对象作为Model的parent,解决问题。

------------------------------

得知吃播中的泡泡龙过世,对肥胖又平添了恐惧。锻炼吧,少年!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章