How can I create a model from a vector of objects so I can use it with a QTableView? it must inherit from what class and must implement what methods?
-
@jdent said in How can I create a model from a vector of objects so I can use it with a QTableView? it must inherit from what class and must implement what methods?:
it must inherit from what class and must implement what methods?
Since it's void QTableView::setModel(QAbstractItemModel *model), see https://doc.qt.io/qt-6/qabstractitemmodel.html#subclassing for a
QAbstractItemModel
, which you could use with a vector data store. See https://doc.qt.io/qt-6/qabstracttablemodel.html#subclassing if you want a table. They tell you which methods you must write. -
@JonB Is this a valid start? Please help me I am lost!
class VectorModel : public QAbstractTableModel { Q_OBJECT std::vector<Claim> rows; public: VectorModel(QObject *parent); ~VectorModel(); int rowCount(const QModelIndex& parent) const override { if(parent.isValid()) return 0; return rows.size(); } int columnCount(const QModelIndex& parent) const override { return 14; } QVariant data(const QModelIndex& index, int role) const override { Claim claim = rows[index.row()]; return claim.id; } };
-
@jdent
Yes, good start. Will produce a read-only model. The reference states all the methods you need to override.In
data()
you must testrole
and only return yours onDisplay
/EditRole
. Else an invalid variant,QVariant()
or call base methodQAbstractTableModel::data(index, role)
. And if you are going to have 14 columns you need to provide that data and takeindex.column()
into account indata()
.If you really only want a model of a vector of something then columns needs to return 1. QAbstractListModel Class would then save you implementing most stuff.
There is some inconsistency: if you want a
QTableView
not aQListView
then presumably your model actual contains more data (columns) than just a vector. Which do you want?