在另一个中使用QAbstractListModel

Dav*_*lez 3 c++ qt datamodel qml qabstractlistmodel

尝试使用Qt/QML为我的应用程序开发数据模型时遇到问题.我已经使用过QAbstractListModel能够将海关数据模型从C++传递到QML,它就像一个简单模型的魅力(例如基于字符串和bool的模型).

但现在我需要建立一个更难的模型,我想知道是否有可能QAbstractListModel在另一个内部使用QAbstractListModel.

让我解释一下自己.我有一个名为model_Abuild 的数据模型:

model_A.h:

#ifndef MODEL_A_H
#define MODEL_A_H

#include <QAbstractListModel>
#include <QList>

class model_A
{
public:
   model_A(const QString& _string1,const QString& _string2,const bool& _bool);
   QString m_string1;
   QString m_string2;
   bool m_bool;
};
class abstractmodel_A : QAbstractListModel
{
   Q_OBJECT
public:
   (here I implemented all the roles functions and overloaded fonctions needed for the model to work)
private:
   QList<model_A> m_model_A;
};        
#endif // ANSWERS_H
Run Code Online (Sandbox Code Playgroud)

然后我需要在另一个模型中使用该模型model_B:

model_B.h:

#ifndef MODEL_B_H
#define MODEL_B_H

#include <QAbstractListModel>
#include <QList>
#include "model_A.h"

class model_B
{
public:
   model_B(const QString& _string1,const QString& _string2,const abstractmodel_A& _modelA);
   QString m_string1;
   QString m_string2;
   abstractmodel_A m_modelA;
};
class abstractmodel_B : QAbstractListModel
{
   Q_OBJECT
public:
   (here I implemented all the roles functions and overloaded fonctions needed for the model to work)
   QList<model_B> m_model_B;
};        
#endif // ANSWERS_H
Run Code Online (Sandbox Code Playgroud)

这是可能的,有QAbstractListModel的DISABLE_COPY的所有限制问题,还是我应该找到另一种方法来构建我的数据模型?

谢谢.

mcc*_*chu 5

model_B,你可以存储一个指针,abstractmodel_A所以DISABLE_COPY不会是一个问题:

class model_B
{
public:
   abstractmodel_A * m_modelA;
};

model_B modelBObject;
modelBObject.m_modelA = new abstractmodel_A(/*parent*/);
Run Code Online (Sandbox Code Playgroud)

接下来,创建model_A_rolein abstractmodel_BQML可以访问委托中的模型A. 内部abstractmodel_B::data功能,你必须转换abstractmodel_A *QVariant.由于abstractmodel_Ainheirts来自QAbstractListModel,即a QObject,类型转换可以简单地完成如下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后回到QML,使用ListView来处理C++模型:

ListView {
    model: model_B
    delegate: Item {
        ListView {
            model: model_A_role
            delegate: DelegateForModelA { /*...*/ }
        }
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

并且DelegateForModelA可以直接访问角色model_A.