3

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

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

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

模型_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

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

模型_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

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

谢谢你。

4

1 回答 1

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*/);

接下来,创建model_A_role以便abstractmodel_BQML 可以在委托中访问模型 A。在abstractmodel_B::data函数内部,您必须转换abstractmodel_A *QVariant. 由于abstractmodel_A继承自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);
    }
}

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

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

并且DelegateForModelA可以直接访问model_A.

于 2015-04-11T10:47:40.113 回答