Use a QAbstractListModel in another one

巧了我就是萌 提交于 2019-12-06 02:09:20

In model_B, you can store a pointer to abstractmodel_A so DISABLE_COPY won't be a problem:

class model_B
{
public:
   abstractmodel_A * m_modelA;
};

model_B modelBObject;
modelBObject.m_modelA = new abstractmodel_A(/*parent*/);

Next, create model_A_role in abstractmodel_B so QML can access model A in delegates. Inside abstractmodel_B::data function, you have to convert abstractmodel_A * to QVariant. Since abstractmodel_A inheirts from QAbstractListModel, which is a QObject, the type conversion can simply be done like this:

QVariant abstractmodel_B::data(const QModelIndex &index, int role) const
{
    //...
    if (role == Model_A_Role)
    {
        return QVariant::fromValue<QObject *>(m_model_B[index.row()].m_modelA);
    }
}

Finally back to QML, use ListView to handle C++ models:

ListView {
    model: model_B
    delegate: Item {
        ListView {
            model: model_A_role
            delegate: DelegateForModelA { /*...*/ }
        }
        //...
    }
}

And DelegateForModelA can directly access roles in model_A.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!