在另一个中使用QAbstractListModel
Use a QAbstractListModel in another one
本文关键字:QAbstractListModel 另一个 更新时间:2023-10-16
我在尝试使用 Qt/QML 为我的应用程序开发数据模型时遇到问题。我已经使用了一个QAbstractListModel
,以便能够将海关数据模型从C++传递到 QML,它就像一个简单的模型(例如基于字符串和布尔值的模型)的魅力一样工作。
但是现在我需要构建一个更困难的模型,我想知道是否可以在另一个QAbstractListModel
中使用QAbstractListModel
。
让我解释一下自己。我有一个名为model_A
这样的数据模型
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
然后我需要在另一个名为 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
这是否可能,对于QAbstractListModel DISABLE_COPY的所有限制问题,或者我应该找到另一种方法来构建我的数据模型?
谢谢。
在model_B
中,你可以存储指向abstractmodel_A
的指针DISABLE_COPY这样就不会有问题:
class model_B
{
public:
abstractmodel_A * m_modelA;
};
model_B modelBObject;
modelBObject.m_modelA = new abstractmodel_A(/*parent*/);
接下来,在abstractmodel_B
中创建model_A_role
,以便 QML 可以访问委托中的模型 A。在abstractmodel_B::data
功能中,您必须 将abstractmodel_A *
转换为QVariant
。由于abstractmodel_A
继承人来自QAbstractListModel
,这是一个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
中的角色。
相关文章:
- 没有找到相关文章